经典游戏坦克大战, 问从位置YOU到位置TARGET的最少步数,类似迷宫的问题 #include <iostream> #include <queue> using namespace std; int m, n, srcx, srcy; char tmap[300][300]; struct POINT{ int x; int y; int sth; //0为无障碍,1为正在去障碍 int step; }; bool flag[300][300]; int dir[4][2] = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}}; void bfs() { queue<POINT> q; POINT curp, next; int i, j; curp.x = srcx; curp.y = srcy; curp.sth = 0; curp.step = 0; q.push(curp); flag[srcx][srcy] = true; while (!q.empty()) { curp = q.front(); q.pop(); for (i=0; i<4; i++) { //不能移动的情况 if (tmap[curp.x][curp.y]=='B' && curp.sth==1) { next.x = curp.x; next.y = curp.y; next.sth = 0; next.step = curp.step + 1; q.push(next); continue; } next.x = curp.x + dir[i][0]; next.y = curp.y + dir[i][1]; next.sth = 0; next.step = curp.step + 1; //越界 if (next.x<0 || next.x>=m || next.y<0 || next.y>=n) continue; //目标位置 if (tmap[next.x][next.y] == 'T') { cout << curp.step+1 << endl; return; } //不可越过障碍 if (tmap[next.x][next.y]=='S' || tmap[next.x][next.y]=='R') continue; //已访问节点 if (flag[next.x][next.y]) continue; flag[next.x][next.y] = true; if (tmap[next.x][next.y]=='E') { q.push(next); continue; } //Brick Wall if (tmap[next.x][next.y]=='B') { next.sth = 1; q.push(next); } } } cout << -1 << endl; } int main() { int i, j; while (cin>>m>>n && m && n) { for (i=0; i<m; i++) for (j=0; j<n; j++) { cin >> tmap[i][j]; if (tmap[i][j] == 'Y') { srcx = i; srcy = j; } } memset(flag, 0, sizeof(flag)); bfs(); } return 0; }