题目链接:https://nanti.jisuanke.com/t/T1212
使用队列
#include<bits/stdc++.h>
using namespace std;
char grid[25][25];
int n,m,move[4][2]={0,-1,0,1,1,0,-1,0},vis[25][25];
struct node{
int x;
int y;
int step;
node(int x_init,int y_init,int step_init){
x = x_init;
y = y_init;
step = step_init;
}
};
int main(){
cin>>n>>m;
queue<node> q;
for(int i = 0;i < n;i++){
for(int j = 0;j < m;j++){
cin>>grid[i][j];
if(grid[i][j] == '*'){
q.push(node(i,j,0));
vis[i][j] = 1;
}
}
}
int len = 0;
while(!q.empty()){
node nn = q.front();
q.pop();
for(int i = 0;i < 4;i++){
int xa = nn.x + move[i][0];
int ya = nn.y + move[i][1];
if(xa < 0 || ya < 0 || xa == n || ya == m) continue;
if(vis[xa][ya] || grid[xa][ya] == '#') continue;
vis[xa][ya] = 1;
if(grid[xa][ya] == '@') {
cout<<nn.step+1<<endl;
return 0;
}
q.push(node(xa,ya,nn.step+1));
}
}
cout<<-1<<endl;
return 0;
}
未使用队列
#include<stdio.h>
struct pos{
int x;
int y;
int len;
};
int flag;
struct pos que[10010];
char bfs[25][25];
int book[25][25];
int move[4][2]={{0,-1},{0,1},{1,0},{-1,0}};
int main(){
int m,n,head,tail;
scanf("%d %d",&m,&n);
for(int i=0;i<m;i++)
for(int j=0;j<n;j++)
scanf(" %c",&bfs[i][j]);
for(int i=0;i<m;i++)
for(int j=0;j<n;j++)
{
if(bfs[i][j]=='@')
{
que[0].x=i;
que[0].y=j;
}
}
que[head].len=0;
tail++;
book[que[0].x][que[0].y]=1;
while(head<tail){
for(int i=0;i<4;i++){
if(book[que[head].x+move[i][0]][que[head].y+move[i][1]]==1){
continue;
}
if(bfs[que[head].x+move[i][0]][que[head].y+move[i][1]]=='#'){
continue;
}
if(que[head].x+move[i][0]>=0&&que[head].y+move[i][1]>=0&&que[head].x+move[i][0]<m&&que[head].y+move[i][1]<n){
que[tail].x=que[head].x+move[i][0];
que[tail].y=que[head].y+move[i][1];
que[tail].len=que[head].len+1;
book[que[head].x+move[i][0]][que[head].y+move[i][1]]=1;
tail++;
}
if(bfs[que[tail-1].x][que[tail-1].y]=='*'){
flag=1;
break;
}
}
if(flag==1){
printf("%d ",que[tail-1].len);
break;
}
head++;
}
if(flag==0){
printf("-1");
}
return 0;
}