刷LeetCode刷到搜索,想先在nyoj上回顾两道之前做过的。
# include<cstdio>
# include<cstdlib>
# include<string.h>
using namespace std;
int n,m;
int map[110][110];
int fx[4][2]={0,1,0,-1,1,0,-1,0};
void BFS(int x,int y){
int nx,ny;
for(int i=0 ;i<4 ;i++){
nx=x+fx[i][0];
ny=y+fx[i][1];
if(nx>=0 && nx<n && ny>=0 && ny<m &&map[nx][ny]== 1){
map[nx][ny]=0;
BFS(nx,ny);
}
}
}
int main(){
int T,count;
scanf("%d",&T);
while(T--){
memset(map,0,sizeof(map));
count=0;
scanf("%d %d",&n,&m);
for(int i=0 ;i<n ;i++)
for(int j=0 ; j<m; j++)
scanf("%d",&map[i][j]);
for(int i=0 ;i<n; i++)
for(int j=0 ;j<m ;j++){
if(map[i][j]==1 ){
count++;
BFS(i,j);
}
}
printf("%d\n",count);
}
}
第二题用结构体+队列处理步数,用count直接处理是得不到结果的
# include<cstdio>
# include<cstdlib>
# include<string.h>
# include<queue>
# include<algorithm>
using namespace std;
int map[9][9]={
{1,1,1,1,1,1,1,1,1},
{1,0,0,1,0,0,1,0,1},
{1,0,0,1,1,0,0,0,1},
{1,0,1,0,1,1,0,1,1},
{1,0,0,0,0,1,0,0,1},
{1,1,0,1,0,1,0,0,1},
{1,1,0,1,0,1,0,0,1},
{1,1,0,1,0,0,0,0,1},
{1,1,1,1,1,1,1,1,1}
};
int vis[9][9];
int fx[4][2]={0,1,0,-1,1,0,-1,0};
struct node{
int x,y,temp;
};
int bfs(int a,int b,int c,int d){
memset(vis,0,sizeof(vis));
int i;
if(a==c && b==d) return 0;
queue<struct node> q;
struct node start={a,b,0};
struct node next;
q.push(start);
while(!q.empty()){
start=q.front();
q.pop();
for(i=0;i<4;i++){
next.x=start.x+fx[i][0];
next.y=start.y+fx[i][1];
next.temp=start.temp+1;// printf("%d %d\n",next.x,next.y);
if(next.x>=0 && next.x<9 &&next.y>=0 &&next.y<9 && map[next.x][next.y]==0 && vis[next.x][next.y]==0){
vis[next.x][next.y]=1;
if(next.x==c && next.y==d) return next.temp;
else q.push(next);
}
}
}
return 0;
}
int main(){
int ans;
int T,a,b,c,d;
scanf("%d",&T);
while(T--){
scanf("%d %d %d %d",&a,&b,&c,&d);
ans=bfs(a,b,c,d);
printf("%d\n",ans);
}
}