题目要求 从‘S’ 到 ‘G’ , 且W是围墙,求到达‘G' 的最短步数
10 12
W........WW.
.WWW.....WWW
....WW...WW.
.........WW.
.........W..
..W......W..
SW.W.....WW.
W.W.W.....W.
.W.WG.....W.
..W.......W.
#include <bits/stdc++.h>
using namespace std;
char str[100][100]; //用于存储每一个字符
int m,n;
int vis[100][100]; //进行判断是否经历过,然后存储到每个点经历的步数
typedef pair<int,int> p; // 定义结构 pair 类型 命名为 p,方便多次使用
int xx[]={1,-1,0,0}; // 我称之为 “方向数组 ”
int yy[]={0,0,1,-1};
int bfs(int a,int b){ //广搜的起点 a b。
queue<p>que; //队列
que.push(p(a,b)); // 进队
while(que.size()){ // BFS 的 while
p q1=que.front(); // q1是用来 取 队列最一开始的数
que.pop(); //出队
if(str[q1.first][q1.second]=='G'){
return vis[q1.first][q1.second];
}
for(int i=0;i<4;i++){
int x_=q1.first+xx[i];
int y_=q1.second+yy[i];
if(x_>=1&&x_<=m&&y_>=1&&y_<=n&&(str[x_][y_]=='.'||str[x_][y_]=='G')){
vis[x_][y_]=vis[q1.first][q1.second]+1;
que.push(p(x_,y_));
}
}
}
return 0;
}
int main()
{
cin >>m>>n;
int x1,y1;
for(int i=1;i<=m;i++){
for(int j=1;j<=n;j++){
cin >>str[i][j];
}
}
for(int i=1;i<=m;i++){
for(int j=1;j<=n;j++){
if(str[i][j]=='S'){
x1=i;
y1=j;
break;
}
}
}
int ans=bfs(x1,y1);
if(ans){
cout<<ans;
}else{
cout<<"no";
}
return 0;
}
【感谢您的观看】