洛谷P1141【01迷宮】
阿新 • • 發佈:2019-03-03
\n bool bsp oid %s printf tps 拓展 show
題目鏈接 P1141 01迷宮
直接暴力的做法就是對於每一個詢問都進行bfs,這樣復雜度最壞可以達到O(mn2),這樣顯然過不了的
我們發現,對於一個點所拓展的路徑上的所有點能走的格子數是一樣的!(然而我沒發現)
所以我們可以dfs求聯通塊,每個聯通塊裏所能走的格子數是一樣的
bfs也可以
#include<bits/stdc++.h> using namespace std; #define check(x,y) (x>0&&x<=n&&y>0&&y<=n) #define nx (x+dx[i]) #defineny (y+dy[i]) char a[1005][1005];
int f[1005][1005]; bool v[1005][1005]; int n, m,now; const int dx[4] = { 1, 0, -1, 0 }, dy[4] = { 0, 1, 0, -1 }; int ans[1000005]; void dfs(int x, int y, int idx){ now++; f[x][y] = idx; for (int i = 0; i<4; i++){ if (check(nx, ny) && !v[nx][ny] && a[x][y] != a[nx][ny]){ v[nx][ny]= true; dfs(nx, ny,idx); } } } int res; int main(){ scanf("%d%d", &n, &m); int idx = 0; for (int i = 1; i <= n; i++) scanf("%s", a[i] + 1); for (int i = 1; i <= n; i++) for (int j = 1; j <= n; j++) if (!v[i][j]){ v[i][j]= true;
now = 0; dfs(i,j,idx); ans[idx] = now; idx++; } int x, y; for (int i = 1; i <= m; i++){ scanf("%d%d", &x, &y); printf("%d\n", ans[f[x][y]]); } return 0; }
洛谷P1141【01迷宮】