算法竞赛基础---BFS与DFS

算法竞赛基础---BFS与DFS

leaf
2022-02-27 / 0 评论 / 32 阅读 / 正在检测是否收录...

include<iostream>

include<cstdio>

include<cstring>

include<queue>

using namespace std;
/*
红黑砖问题(老鼠走迷宫问题)
经典BFS
RED AND BLACK
There is a rectangular room, covered with square tiles. Each tile is colored either red or black.
A man is standing on a black tile. From a tile, he can move to one of four adjacent tiles.
But he can't move on red tiles, he can move only on black tiles.
Write a program to count the number of black tiles which he can reach by repeating the moves described above.
Input
The input consists of multiple data sets. A data set starts with a line containing two positive integers W and H;
W and H are the numbers of tiles in the x- and y- directions, respectively. W and H are not more than 20.
There are H more lines in the data set, each of which includes W characters.
Each character represents the color of a tile as follows.
'.' - a black tile
'#' - a red tile
'@' - a man on a black tile(appears exactly once in a data set)
Output
For each data set, your program should output a line which contains the number of tiles he can reach from the initial tile (including itself).
*/

int dir4={{-1,0},{0,-1},{1,0},{0,1}};//左上右下
const int MAXN=30;
int Wx,Hy;//Wx表示的迷宫的行,Hy表示迷宫的列
char mpMAXN;
struct node{

int x;
int y;

};
queue<node> q ;

define check(x,y)(x>=0&&x<Wx&&y>=0&&y<Hy)//判断是否出界

int ans=0;//记录结果
void BFS(int x,int y){

ans=1;
node now,next;
now.x=x;
now.y=y;
q.push(now);//起点入栈
while(!q.empty()){
    now=q.front();
    q.pop();
    for(int i=0;i<4;i++){
        next.x=now.x+dir[i][0];
        next.y=now.y+dir[i][1];//向四个方位前进
        if(check(next.x,next.y)&&mp[next.x][next.y]=='.'){
             mp[next.x][next.y]='#';
            ans++;
            q.push(next);//将符合条件的点入栈  
        } 
    }
} 

}
void DFS(int x,int y){

mp[x][y]='#';
ans++;
for(int i=0;i<4;i++){
int newx=x+dir[i][0];
int newy=y+dir[i][1];
if(check(newx,newy)&&mp[newx][newy]=='.'){
    DFS(newx,newy);
    
}
}

}
int main(){

int dx=0,dy=0,x,y;
memset(mp,0,sizeof(mp));
while(cin>>Wx>>Hy){//Wx为列,Hy为行 
if(Wx==0&&Hy==0)break;
for(y=0;y<Hy;y++){
    for(x=0;x<Wx;x++){
        cin>>mp[x][y];
        if(mp[x][y]=='@'){//得到起点 
            dx=x;
            dy=y;
    }
}
    

}

ans=0;
//    BFS(dx,dy);
DFS(dx,dy);
cout<<ans<<endl;

}

return 0;

}

1

评论

博主关闭了所有页面的评论