题目链接。
分析:
本题BFS A不了。
00100
00001
01020
00000
00010
00010
00010
00010
00030
对于这样的数据,本来应当是 5 步,但bfs却 4 步。具体原因可以仔细看一下上面的样例。
应当dfs穷举所有的可能,找出最短的。
#include <iostream> #include <cstdio> #include <queue> using namespace std; const int maxn = 23; const int INF = (1<<29); int dx[] = {1, -1, 0, 0}; int dy[] = {0, 0, -1, 1}; int h, w, G[maxn][maxn], min_step; void dfs(int x, int y, int step) { int nx, ny; if(step >= 10) return ; for(int d=0; d<4; d++) { nx = x; ny = y; nx = x+dx[d]; ny = y+dy[d]; if(nx < 0 || ny < 0 || nx >= h || ny >= w) continue ; if(G[nx][ny] == 1) continue; //靠着墙 while(!(G[nx][ny] == 1 || G[nx][ny] == 3)) { nx += dx[d]; ny += dy[d]; if(nx < 0 || ny < 0 || nx >= h || ny >= w) break; } if(nx < 0 || ny < 0 || nx >= h || ny >= w) continue; //这个判断有必要 if(G[nx][ny] == 3) { //终点 min_step = min(min_step, step+1); } else if(G[nx][ny] == 1){ //墙 G[nx][ny] = 0; dfs(nx-dx[d], ny-dy[d], step+1); G[nx][ny] = 1; } } } int main(){ int sx, sy; while(scanf("%d%d", &w, &h) == 2) { if(w == 0 && h == 0) break; min_step = INF; for(int i=0; i<h; i++) { for(int j=0; j<w; j++) { scanf("%d", &G[i][j]); } } for(int i=0; i<h; i++) { for(int j=0; j<w; j++) { if(G[i][j] == 2) { sx = i; sy = j; } } } dfs(sx, sy, 0); if(min_step != INF) { printf("%d ", min_step); } else printf("-1 "); } return 0; }