BFS。wa了一下午,原来是YES,写成了Yes。
1 #include2 #include 3 #include 4 #include 5 using namespace std; 6 7 typedef struct node_st{ 8 int x, y; 9 int dir;10 int turn;11 node_st() {}12 node_st(int xx, int yy, int ddir, int tturn) {13 x = xx; y = yy; dir = ddir; turn = tturn;14 }15 } node_st;16 17 int map[1005][1005];18 int n, m;19 int dirs[4][2] = { { 0,1},{ 0,-1},{ 1,0},{-1,0}};20 char turns[1005][1005];21 22 bool bfs(int bx, int by, int ex, int ey) {23 queue que;24 bool val = false;25 node_st node;26 int x, y, dir, turn;27 28 memset(turns, 0, sizeof(turns));29 turns[bx][by] = 1;30 que.push(node_st(bx, by, -1, 0));31 32 while ( !que.empty() ) {33 node = que.front();34 //printf("x=%d, y=%d, dir=%d, turn=%d\n", node.x, node.y, node.dir, node.turn);35 if (node.x == ex && node.y == ey) {36 val = true;37 break;38 }39 que.pop();40 for (int i=0; i<4; ++i) {41 x = node.x + dirs[i][0];42 y = node.y + dirs[i][1];43 dir = i;44 turn = node.turn;45 if (x<1 || x>n || y<1 || y>m)46 continue;47 if (map[x][y] && (x!=ex || y!=ey))48 continue;49 if (dir!=node.dir && node.dir!=-1)50 ++turn;51 //printf("\tx=%d, y=%d, dir=%d, turn=%d\n", x, y, dir, turn);52 if (turn > 2)53 continue;54 if (turns[x][y]==0 || turn+1 <= turns[x][y]) {55 turns[x][y] = turn+1;56 que.push(node_st(x, y, dir, turn));57 }58 }59 }60 61 return val;62 }63 64 int main() {65 int q, x1, x2, y1, y2;66 int i, j;67 68 while (scanf("%d %d", &n, &m)!=EOF && (n||m)) {69 for (i=1; i<=n; ++i)70 for (j=1; j<=m; ++j)71 scanf("%d", &map[i][j]);72 scanf("%d", &q);73 while (q--) {74 scanf("%d %d %d %d", &x1, &y1, &x2, &y2);75 if (x1==x2 && y1==y2) {76 printf("NO\n");77 continue;78 }79 if (map[x1][y1]!=map[x2][y2] || map[x1][y1]==0 || map[x2][y2]==0) {80 printf("NO\n");81 continue;82 }83 if ( bfs(x1, y1, x2, y2) )84 printf("YES\n");85 else86 printf("NO\n");87 }88 }89 90 return 0;91 }