bzoj2252 矩阵距离
很好奇这种 普及- 的题为什么会是权限题......
我一开始想用枚举 + 搜索,看书后发现自己脑抽了。直接BFS即可。
1 #include <cstdio> 2 #include <queue> 3 #include <cstring> 4 5 struct Sta { 6 int x, y, step; 7 Sta(int x = 0, int y = 0) { 8 this->x = x; 9 this->y = y; 10 } 11 }; 12 13 const int N = 1010; 14 int G[N][N], dis[N][N]; 15 16 const int dx[4] = {0, 0, 1, -1}; 17 const int dy[4] = {1, -1, 0, 0}; 18 19 int main() { 20 int m, n; 21 std::queue<Sta> Q; 22 memset(dis, -1, sizeof(dis)); 23 scanf("%d%d", &n, &m); 24 for(int i = 1; i <= n; i++) { 25 for(int j = 1; j <= m; j++) { 26 char c = getchar(); 27 while(c < '0' || c > '1') { 28 c = getchar(); 29 } 30 G[i][j] = c - 48; 31 if(G[i][j]) { 32 dis[i][j] = 0; 33 Q.push(Sta(i, j)); 34 } 35 } 36 } 37 38 for(int i = 0; i <= n + 1; i++) { 39 dis[i][0] = dis[i][m + 1] = 0; 40 } 41 for(int i = 1; i <= m; i++) { 42 dis[0][i] = dis[n + 1][i] = 0; 43 } 44 45 while(!Q.empty()) { 46 Sta op = Q.front(); 47 Q.pop(); 48 for(int i = 0; i <= 3; i++) { 49 int tx = op.x + dx[i]; 50 int ty = op.y + dy[i]; 51 if(dis[tx][ty] >= 0) { 52 continue; 53 } 54 dis[tx][ty] = dis[op.x][op.y] + 1; 55 Q.push(Sta(tx, ty)); 56 } 57 } 58 59 for(int i = 1; i <= n; i++) { 60 for(int j = 1; j <= m; j++) { 61 printf("%d ", dis[i][j]); 62 } 63 if(i < n) { 64 puts(""); 65 } 66 } 67 68 return 0; 69 }
代码里的G[N][N]应该是多余的...