bfs.
1 /* 2822 */ 2 #include <iostream> 3 #include <cstdio> 4 #include <cstring> 5 #include <cstdlib> 6 #include <queue> 7 using namespace std; 8 9 #define MAXN 1005 10 #define INF 0xffffff 11 12 typedef struct node_t { 13 int d, x, y; 14 node_t() {} 15 node_t(int xx, int yy, int dd) { 16 x = xx; y = yy; d = dd; 17 } 18 friend bool operator <(node_t a, node_t b) { 19 return a.d > b.d; 20 } 21 } node_t; 22 23 int visit[MAXN][MAXN]; 24 char map[MAXN][MAXN]; 25 int n, m; 26 int bx, by, ex, ey; 27 int dir[4][2] = { 28 -1,0,1,0,0,1,0,-1 29 }; 30 31 inline bool check(int x, int y) { 32 return x<0 || x>=n || y<0 || y>=m; 33 } 34 35 int bfs() { 36 int x = bx, y = by, d = 0; 37 int i, j, k; 38 priority_queue<node_t> Q; 39 node_t nd; 40 41 Q.push(node_t(x, y, d)); 42 visit[x][y] = 0; 43 44 while (!Q.empty()) { 45 nd = Q.top(); 46 if (nd.x==ex && nd.y==ey) 47 return nd.d; 48 Q.pop(); 49 for (i=0; i<4; ++i) { 50 x = nd.x + dir[i][0]; 51 y = nd.y + dir[i][1]; 52 if (check(x, y)) 53 continue; 54 if (map[x][y] == 'X') 55 d = nd.d; 56 else 57 d = nd.d + 1; 58 if (d < visit[x][y]) { 59 visit[x][y] = d; 60 Q.push(node_t(x, y, d)); 61 } 62 } 63 } 64 65 return 0; 66 } 67 68 int main() { 69 int i, j, k; 70 71 #ifndef ONLINE_JUDGE 72 freopen("data.in", "r", stdin); 73 #endif 74 75 while (scanf("%d %d", &n, &m)!=EOF && (n||m)) { 76 for (i=0; i<n; ++i) { 77 scanf("%s", map[i]); 78 for (j=0; j<m; ++j) 79 visit[i][j] = INF; 80 } 81 scanf("%d%d%d%d",&bx,&by,&ex,&ey); 82 --bx; --by; --ex; --ey; 83 k = bfs(); 84 printf("%d\n", k); 85 } 86 87 return 0; 88 }