2022.2.27

2022.2.27

 

#include<cstdio>
#include<iostream>
#include<algorithm>
#include<cstring>
#include<queue>
using namespace std;
char map[110][110];
bool map1[110][110]={0};
typedef struct node
{
int x;
int y;
int tim;
};
int n;
int mov1[4]={1,-1,0,0};
int mov2[4]={0,0,1,-1};
int bfs(int x,int y)
{
queue<node>Q;
node s1,s2;
s1.x=x;
s1.y=y;
s1.tim=0;
Q.push(s1);
while(!Q.empty())
{
s2=Q.front();
Q.pop();
if(map[s2.x][s2.y]=='B')
{
return s2.tim;
}
for(int i=0;i<4;i++)
{
s1.x=s2.x+mov1[i];
s1.y=s2.y+mov2[i];
if(!map1[s1.x][s1.y]&&s1.x>=0&&s1.x<n&&s1.y>=0&&s1.y<n&&map[s1.x][s1.y]!=map[s2.x][s2.y])
{
s1.tim=s2.tim+1;
map1[s1.x][s1.y]=1;
Q.push(s1);
}
}
}
return -1;
}
int main()
{
int x,y,t=0;
scanf("%d",&n);
for(int i=0;i<n;i++)
{
for(int j=0;j<n;j++)
{
cin>>map[i][j];
if(map[i][j]=='A')
{
x=i;
y=j;
}
}
}
t=bfs(x,y);
printf("%d\n",t);
return 0;
}

很普通的dfs题,用一个队列就可以AC

上一篇:MIT6.830 lab1 SimpleDb


下一篇:hive 取中位数的两种方式