Files
Data-Structure/Algorithm/Graph/BFS/Maze.cpp
2025-08-30 21:59:50 +08:00

67 lines
1.4 KiB
C++
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

#include <iostream>
#include <utility>
#include <deque>
using namespace std;
//竖着来
int dx[4] = {0, 0, -1, 1};
int dy[4] = {1, -1, 0, 0};
int dxx[8] = {-1, -1, -1, 0, 0, 1, 1, 1};
int dyy[8] = {1, 0, -1, 1, -1, 1, 0, -1};
int main(){
deque<pair<int, int>> q;
int n, m;
//行列
cin >> n >> m;
int startx, starty;
//入口
cin >> startx >> starty;
deque<deque<int>> maze;
deque<deque<bool>> visited;
deque<deque<int>> dist(n, deque<int>(m, 0)); // 距离数组
maze.resize(n);
visited.resize(n, deque<bool>(m, false));
int tmp;
//0表示墙1表示路
for(int i = 0; i < n; i++){
for(int j = 0; j < m; j++){
cin >> tmp;
maze[i].push_back(tmp);
}
}
tmp = 0;
q.push_back(make_pair(startx, starty));
while(!q.empty()){
pair<int, int> u = q.front();
q.pop_front();
int x = u.first, y = u.second;
visited[x][y] = true;
for(int i = 0; i < 4; i++){
if(x + dx[i] >= 0 && x + dx[i] < n && y + dy[i] >= 0 && y + dy[i] < m && !visited[x + dx[i]][y + dy[i]] && maze[x + dx[i]][y + dy[i]] == 1){
visited[x + dx[i]][y + dy[i]] = true;
dist[x + dx[i]][y + dy[i]] = dist[x][y] + 1; // 更新距离
q.push_back(make_pair(x + dx[i], y + dy[i]));
}
}
}
cout << endl;
for(int i = 0; i < n; i++){
for(int j = 0; j < m; j++){
cout << dist[i][j] << " ";
}
cout << endl;
}
return 0;
}
/*
6 5
0 0
1 1 0 1 1
1 0 1 1 1
1 0 1 0 0
1 0 1 1 1
1 1 1 0 1
1 1 1 1 1
*/