DFS deep first search & BFS breadth first search

Red and Black  HDU-1312

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). 

Sample Input

6 9
....#.
.....#
......
......
......
......
......
#@...#
.#..#.
11 9
.#.........
.#.#######.
.#.#.....#.
.#.#.###.#.
.#.#..@#.#.
.#.#####.#.
.#.......#.
.#########.
...........
11 6
..#..#..#..
..#..#..#..
..#..#..###
..#..#..#@.
..#..#..#..
..#..#..#..
7 7
..#.#..
..#.#..
###.###
...@...
###.###
..#.#..
..#.#..
0 0

Sample Output

45
59
6
13

题意: 

.可以走,#不能走,@是人的起点,问这个人能走到的.的数量

 

#include <iostream>
#include <string.h>
using namespace std;
int w, h, step;//w列 h行
char mp[25][25];
int vis[25][25];
int dx[4] = {0, 0, 1, -1};//上下左右
int dy[4] = {1, -1, 0, 0};

void DFS(int x, int y) {
    if (x < 0 || y < 0 || x >= h || y >= w || mp[x][y] == '#' || vis[x][y])
        return ;//如果不能走,跳出本次递归函数
    step++;
    for (int i = 0; i < 4; i++) {
        vis[x][y] = true;
        int fx = x + dx[i];
        int fy = y + dy[i];
        DFS(fx, fy);
    }
}

int main() {
    while (cin >> w >> h && (w || h)) {
        memset(vis, 0, sizeof(vis));
        step = 0;
        for (int i = 0; i < h; i++) //h行,一行一行的输入
            cin >> mp[i];//scanf("%s", mp[i]);
        for (int i = 0; i < h; i++) { //w列h行
            for (int j = 0; j < w; j++) {
                if (mp[i][j] == '@') { //以@的坐标为起点
                    DFS(i, j);
                    break;
                }
            }
        }
        cout << step <<endl;
    }
    return 0;
}

Oil Deposits  HDU-1241

 

The GeoSurvComp geologic survey company is responsible for detecting underground oil deposits. GeoSurvComp works with one large rectangular region of land at a time, and creates a grid that divides the land into numerous square plots. It then analyzes each plot separately, using sensing equipment to determine whether or not the plot contains oil. A plot containing oil is called a pocket. If two pockets are adjacent, then they are part of the same oil deposit. Oil deposits can be quite large and may contain numerous pockets. Your job is to determine how many different oil deposits are contained in a grid. 

Input

The input file contains one or more grids. Each grid begins with a line containing m and n, the number of rows and columns in the grid, separated by a single space. If m = 0 it signals the end of the input; otherwise 1 <= m <= 100 and 1 <= n <= 100. Following this are m lines of n characters each (not counting the end-of-line characters). Each character corresponds to one plot, and is either `*', representing the absence of oil, or `@', representing an oil pocket. 

Output

For each grid, output the number of distinct oil deposits. Two different pockets are part of the same oil deposit if they are adjacent horizontally, vertically, or diagonally. An oil deposit will not contain more than 100 pockets. 

Sample Input

1 1
*
3 5
*@*@*
**@**
*@*@*
1 8
@@****@*
5 5 
****@
*@@*@
*@**@
@@@*@
@@**@
0 0 

Sample Output

0
1
2
2
#include<bits/stdc++.h>
using namespace std;
int m,n;//m行n列
char mp[110][110];
int vis[110][110];
int dx[8]={-1,1,0,0,-1,-1,1,1};
int dy[8]={0,0,-1,1,-1,1,-1,1};

void DFS(int x,int y)
{
    if(x<0||y<0||x>=m||y>=n||vis[x][y]==0)
        return ;

    else
    {
        vis[x][y]=0;//走过的
        for(int i=0;i<8;i++)
        {
            int fx=x+dx[i];
            int fy=y+dy[i];
            DFS(fx,fy);
        }
    }
}

int main()
{
    while(scanf("%d%d",&m,&n)!=EOF&&(m||n))
    {
        memset(mp,0,sizeof(mp));
        memset(vis,0,sizeof(vis));
        for(int i=0;i<m;i++)
            scanf("%s",mp[i]);
        for(int i=0;i<m;i++)//先把这个图处理一下
        {
            for(int j=0;j<n;j++)
            {
                if(mp[i][j]=='*')
                    vis[i][j]=0;//0代表没有油矿
                else
                    vis[i][j]=1;
            }
        }
        int sum=0;
        for(int i=0;i<m;i++)
        {
            for(int j=0;j<n;j++)
            {
                if(vis[i][j]==1)//如果有油矿
                {
                    DFS(i,j);//把连通的油矿标为0
                    sum++;
                }
            }
        }
        printf("%d\n",sum);

    }
    return 0;
}

BFS模板

用 pair<int,int>存的

const int maxn=100+5;
const int INF=1e8;
typedef pair<int,int> pii;//pair<int,int>和int float一样是个类型
char mp[maxn][maxn];
int d[maxn][maxn];
int n,m;
int sx,sy;//起点
int dx[4]={1,0,-1,0};
int dy[4]={0,1,0,-1};
int bfs()
{
    queue<pii> que;
    for(int i=0;i<n;i++)//初始化
        for(int j=0;j<m;j++)
            d[i][j]=INF;
    que.push(pii(sx,sy));//起点入队
    d[sx][sy]=0;
    while(que.size()){
       pii p=que.front();//队头赋给p
        que.pop();
        if(mp[p.first][p.second]=='终点')//如果队头装的是终点,return
            return d[p.first][p.second];
        for(int i=0;i<4;i++){
            int fx=p.first+dx[i];
            int fy=p.second+dy[i];
            if(0<=fx&&fx<n&&0<=fy&&fy<m&&mp[fx][fy]!='#'&&d[fx][fy]==INF){
                que.push(pii(fx,fy));
                d[fx][fy]=d[p.first][p.second]+1;
            }
        }
    }
}

用结构体存的

char mp[201][201];
int vis[201][201];
int sx,sy;//起点
int n,m;
int dx[4]={0,0,1,-1};
int dy[4]={1,-1,0,0};
struct node
{
    int x;
    int y;
    int step;
};
int bfs()
{
    queue<node>que;
    memset(vis,0,sizeof(vis));
    node now,next;
    now.step=0;
    now.x=sx;
    now.y=sy;
    que.push(now);
    vis[sx][sy]=1;
    while(!que.empty()){
        now=que.front();
        que.pop();
        if(mp[now.x][now.y]=='终点')
            return now.step;
        for(int i=0;i<4;i++){
            int fx=now.x+dx[i];
            int fy=now.y+dy[i];
            if(fx>=0&&fx<n&&fy>=0&&fy<m&&!vis[fx][fy]&&mp[fx][fy]!='#'){
                vis[fx][fy]=1;
                next.x=fx;
                next.y=fy;
                next.step=now.step+1;
                que.push(next);
            }
        }
    }
}

下面这个是一道BFS题目

Rescue

Angel was caught by the MOLIGPY! He was put in prison by Moligpy. The prison is described as a N * M (N, M <= 200) matrix. There are WALLs, ROADs, and GUARDs in the prison.

Angel's friends want to save Angel. Their task is: approach Angel. We assume that "approach Angel" is to get to the position where Angel stays. When there's a guard in the grid, we must kill him (or her?) to move into the grid. We assume that we moving up, down, right, left takes us 1 unit time, and killing a guard takes 1 unit time, too. And we are strong enough to kill all the guards.

You have to calculate the minimal time to approach Angel. (We can move only UP, DOWN, LEFT and RIGHT, to the neighbor grid within bound, of course.)

Input

First line contains two integers stand for N and M.

Then N lines follows, every line has M characters. "." stands for road, "a" stands for Angel, and "r" stands for each of Angel's friend.

Process to the end of the file.

Output

For each test case, your program should output a single integer, standing for the minimal time needed. If such a number does no exist, you should output a line containing "Poor ANGEL has to stay in the prison all his life."

Sample Input

7 8
#.#####.
#.a#..r.
#..#x...
..#..#.#
#...##..
.#......
........

Sample Output

13

r代表朋友,a代表天使,x代表小怪,由于朋友可能不止一个,所以考虑用天使找朋友的方法做

a找r,#为障碍,  · 为道路,一个 · 需要耗费一个单位时间,一个x(小怪)需要耗费两个单位时间

BFS还没想出来怎么做 ,先把半成品贴出来,

 

#include<iostream>
#include<stdio.h>
#include<queue>
#include<algorithm>
#include<string.h>
using namespace std;
typedef pair<int,int> pii;
const int maxn=200+5;
const int INF = 1000000;//0x3f3f3f3f;
int mp[maxn][maxn];
int d[maxn][maxn];
int n,m;
int sx,sy;
int gx[maxn],gy[maxn];
int cnt;
int u;
int flag;
int ans[maxn];
int dx[4]={0,0,1,-1};
int dy[4]={1,-1,0,0};
void bfs()
{
        int k=cnt-1;
        queue<pii> que;
        pii p;
        for(int i=0;i<n;i++)
            for(int j=0;j<m;j++)
                d[i][j]=INF;
        d[sx][sy]=0;
        que.push(pii(sx,sy));
        while(!que.empty()){
            p=que.front();
            que.pop();
            if(p.first==gx[k]&&p.second==gy[k]){
                flag=1;
                ans[u++]=d[gx[k]][gy[k]];
                k--;
                if(k<0)
                    break;
            }
            for(int i=0;i<4;i++){
                int fx=p.first+dx[i];
                int fy=p.second+dy[i];
                if(fx>=0&&fx<n&&fy>=0&&fy<m&&mp[fx][fy]!='#'&&d[fx][fy]==INF){
                    que.push(pii(fx,fy));
                    if(mp[fx][fy]=='x')
                        d[fx][fy]=d[p.first][p.second]+2;
                    else
                        d[fx][fy]=d[p.first][p.second]+1;
                }
            }
        }
}

int main()
{
    while(cin>>n>>m){
        cnt=0;
        u=0;
        flag=0;
        for(int i=0;i<n;i++)
            scanf("%s",mp[i]);
        for(int i=0;i<n;i++){
            for(int j=0;j<m;j++){
                if(mp[i][j]=='r'){
                    gx[cnt]=i;
                    gy[cnt]=j;
                    cnt++;
                }
            }
        }
        for(int i=0;i<n;i++)
            for(int j=0;j<m;j++)
                if(mp[i][j]=='a'){
                    sx=i;
                    sy=j;
                    break;
                }
        bfs();
        if(flag==0){
            cout<<"Poor ANGEL has to stay in the prison all his life."<<endl;
        }
        else{
            sort(ans,ans+u-1);
            cout<<ans[0]<<endl;
        }
    }
    return 0;
}

 借鉴网友的误解:   也没有求步数的最小值,  不过使用结构体存储的,还没有用过,可以了解一下,

#include<bits/stdc++.h>
using namespace std;
char mp[201][201];
int vis[201][201];
int sx,sy,n,m;
int dx[4]={0,0,1,-1};
int dy[4]={1,-1,0,0};
struct node
{
    int x;
    int y;
    int step;
};
int bfs()
{
    queue<node>que;
    memset(vis,0,sizeof(vis));
    node now,next;
    now.step=0;
    now.x=sx;
    now.y=sy;
    que.push(now);
    vis[sx][sy]=1;
    while(!que.empty()){
        now=que.front();
        que.pop();
        if(mp[now.x][now.y]=='r')
            return now.step;
        for(int i=0;i<4;i++){
            int fx=now.x+dx[i];
            int fy=now.y+dy[i];
            if(fx>=0&&fx<n&&fy>=0&&fy<m&&!vis[fx][fy]&&mp[fx][fy]!='#'){
                vis[fx][fy]=1;
                next.x=fx;
                next.y=fy;
                if(mp[fx][fy]=='x')
                    next.step=now.step+2;
                else
                    next.step=now.step+1;
                que.push(next);
            }
        }
    }
    return -1;
}
int main()
{
    int ans;
    while(scanf("%d%d",&n,&m)!=EOF){
        for(int i=0;i<n;i++){
            scanf("%s",mp[i]);
            for(int j=0;j<m;j++){//这个遍历方法6
                 if(mp[i][j]=='a'){
                    sx=i;
                    sy=j;
                }
            }
        }
        ans=bfs();
        if(ans==-1)
            printf("Poor ANGEL has to stay in the prison all his life.\n");
        else
            printf("%d\n",ans);
    }
    return 0;
}

用dfs AC的

#include<bits/stdc++.h>
using namespace std;
int n,m;
int sx,sy;
char mp[250][250];
int vis[250][250];
int ok,ans;
void dfs(int x,int y,int step)
{
    if(x<0||x>n-1||y<0||y>m-1||vis[x][y]==1||mp[x][y]=='#')
        return ;
    if(step>=ans)
        return ;//剪枝
    if(mp[x][y]=='r'){
        ok=1;
        ans=min(step,ans);
        return ;
    }
    if(mp[x][y]=='x')
        step++;
    vis[x][y]=1;
    dfs(x+1,y,step+1);
    dfs(x-1,y,step+1);
    dfs(x,y+1,step+1);
    dfs(x,y-1,step+1);
    vis[x][y]=0;
}
int main()
{
    while(~scanf("%d%d",&n,&m)){
        memset(vis,0,sizeof(vis));
        for(int i=0; i<n; i++)
            scanf("%s",mp[i]);
        for(int i=0; i<n; i++){
            for(int j=0; j<m; j++){
                if(mp[i][j]=='a'){
                    sx=i;
                    sy=j;
                    break;
                }
            }
        }
        ok=0;
        ans=999999999;
        dfs(sx,sy,0);
        if(ok)
            printf("%d\n",ans);
        else
            printf("Poor ANGEL has to stay in the prison all his life.\n");
    }
}

走迷宫(maze)

输入:

5 5
s#...
.#.#.
.....
.#.#.
...#t

 

#include<bits/stdc++.h>
using namespace std;
const int maxn=100+5;
const int INF=1e8;
typedef pair<int,int> pii;//pair<int,int>和int float一样是个类型
char mp[maxn][maxn];
int d[maxn][maxn];
int n,m;
int sx,sy;//起点
int gx,gy;//终点
int dx[4]={1,0,-1,0};
int dy[4]={0,1,0,-1};
int bfs()
{
    queue<pii> que;
    for(int i=0;i<n;i++)//初始化
        for(int j=0;j<m;j++)
            d[i][j]=INF;
    que.push(pii(sx,sy));//起点入队
    d[sx][sy]=0;
    while(que.size()){
       pii p=que.front();//队头赋给p
        que.pop();
        if(p.first==gx&&p.second==gy)//如果队头装的是终点,跳出
            break;
        for(int i=0;i<4;i++){
            int fx=p.first+dx[i];
            int fy=p.second+dy[i];
            if(0<=fx&&fx<n&&0<=fy&&fy<m&&mp[fx][fy]!='#'&&d[fx][fy]==INF){
                que.push(pii(fx,fy));
                d[fx][fy]=d[p.first][p.second]+1;
            }
        }
    }
    return d[gx][gy];
}
int main()
{
    cin>>n>>m;
    int ans;
    for(int i=0;i<n;i++)
        cin>>mp[i];
     for(int i=0; i<n; ++i)//先把终点找出来
            for(int j=0; j<n; j++)
                if(mp[i][j]=='t'){
                    gx=i;
                    gy=j;
                }
    for(int i=0;i<n;i++){//再把起点找出来
        for(int j=0;j<m;j++){
            if(mp[i][j]=='s'){
                sx=i;
                sy=j;
                ans= bfs();
                break;
            }
        }
    }
    cout<<ans<<endl;
    return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值