(回顾)水池数目 &&最少步数

刷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);
    }


}
        



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值