BFS模板
输入一个m×n的地图(含有0和1两种状态,1不能走),起始点和目标点的坐标,找到最短路。
#include <iostream> #include <queue> #define SIZE 1000 using namespace std; queue<int> q_x, q_y, q_pos; int step[4][2] = { {1,0},{0,1},{-1,0},{0,-1} }; int m, n, board[SIZE][SIZE], start_x, start_y, target_x, target_y; bool vis[SIZE][SIZE]; void bfs() { bool flag = false; while (!q_x.empty() && !q_y.empty()) { for (int k = 0; k < 4; ++k) { int tx = q_x.front() + step[k][0]; int ty = q_y.front() + step[k][1]; if (tx < 1 || ty < 1 || tx > n || ty > m) continue; if (!board[tx][ty] && !vis[tx][ty]) { vis[tx][ty] = true; q_x.push(tx); q_y.push(ty); q_pos.push(q_pos.front() + 1); } if (tx == target_x&&ty == target_y) { flag = true; break; } } if (flag) break; q_x.pop(); q_y.pop(); q_pos.pop(); } return; } int main() { while (cin >> m >> n) { for (int i = 1; i <= m; ++i) { for (int j = 1; j <= n; ++j) { cin >> board[i][j]; } } cin >> start_x >> start_y >> target_x >> target_y; q_x.push(start_x); q_y.push(start_y); q_pos.push(0); vis[start_x][start_y] = true; bfs(); cout << q_pos.back() << endl; } return 0; }