** 刷题笔记–走迷宫**
如果小伙伴还不太了解迷宫问题,可以在B站搜索:麦克老师讲算法–BFS解决迷宫问题
个人觉得讲得很清晰!
// write your code here cpp
#include<queue>
#include<vector>
#include<iostream>
using namespace std;
struct point{
int x;
int y;
int step;
};
int bfs(vector<string>&mp)
{
int dx[4]={0,1,0,-1};
int dy[4]={1,0,-1,0};
struct point start{0,1,0};
struct point endp{9,8,0};
queue<point>q;
q.push(start);
vector<vector<bool>>used(10,vector<bool>(10,false));
used[start.x][start.y]=true;
while(!q.empty()){
int x=q.front().x,y=q.front().y;
if(x==endp.x&&y==endp.y){
return q.front().step;
}
for(int i=0;i<=3;++i){
int tx,ty;
tx=x+dx[i];
ty=y+dy[i];
if(tx>=0&&tx<10&&ty>=0&&ty<10&&mp[tx][ty]=='.'&&used[tx][ty]==false)
{
point tmp;
tmp.x=tx;
tmp.y=ty;
tmp.step=q.front().step+1;
q.push(tmp);
used[tx][ty]=true;
}
}
q.pop();
}
return 0;
}
int main(){
vector<string>mp(10);
int i=0;
while(cin>>mp[i++]){
if(i==10){
cout<<bfs(mp)<<endl;
i=0;
}
}
return 0;
}
#include<iostream>
#include<queue>
using namespace std;
char map[501][501];
int mark[501][501];
int n, m;
struct node {
int x, y;
int t;
};
int mynext[4][2]{
0,1,
1,0,
0,-1,
-1,0
};
queue<node> Q;
int BFS(int x, int y) {
while (!Q.empty()) {
node now = Q.front();
Q.pop();
for (int i = 0; i < 4; i++) {
int nx = now.x + mynext[i][0];
int ny = now.y + mynext[i][1];
if (nx < 0 || nx >= n || ny < 0 || ny >= m || map[nx][ny] == '#'|| mark[nx][ny] == 1) { continue; }
mark[nx][ny] = 1;
node tmp;
tmp.x = nx; tmp.y = ny;
tmp.t = now.t + 1;
Q.push(tmp);
if (map[nx][ny] == 'T') { return tmp.t; }
}
}
return -1;
}
int main() {
node first;
while (cin >> n>>m ) {
while (!Q.empty()) Q.pop();
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
cin >> map[i][j];
if (map[i][j] == 'S') {
first.x = i; first.y = j;
mark[first.x][first.y] = 1;
}
}
}
first.t = 0;
Q.push(first);
cout << BFS(first.x, first.y) << endl;
}
system("pause");
return 0;
}