dfs做题记录

dfs求连通块

第一题: HDU1241 Oil Deposits

Problem Description

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<iostream>
#include<cstdio>
using namespace std;
int m,n;
char map[105][105];
int dir[8][2]={{0,1},{0,-1},{1,0},{-1,0},{1,1},{1,-1},{-1,1},{-1,-1}};
void dfs(int x,int y){
    for(int i=0;i<8;i++){
        int xx=x+dir[i][0];
        int yy=y+dir[i][1];

        if(xx>=0&&xx<m&&yy>=0&&yy<n){
            if(map[xx][yy]=='@'){
                map[xx][yy]='*';
                dfs(xx,yy);
            }

        }

    }
}
int main(){
    while(scanf("%d%d",&m,&n)){
        if(m==0&&n==0)break;
        //getchar();
        for(int i=0;i<m;i++){
            for(int j=0;j<n;j++){
//直接用cin的好处,可以无视'\n'也就是说cin无法输入换行符,但是getchar和scanf会输入换行符
                cin>>map[i][j];
            }
        }
        int sum=0;
        for(int i=0;i<m;i++){
            for(int j=0;j<n;j++){
                if(map[i][j]=='@'){
                    map[i][j]='*';
                    sum++;
                    dfs(i,j);
                }
            }
        }

        printf("%d\n",sum);
    }
    return 0;
}

一道类似的题目

第二题: HDU1312 Red and Black

Problem Description

扫描二维码关注公众号,回复: 7023082 查看本文章

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

ACcode

#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
int w,h;
int s_x,s_y;
int total=0;
char map[22][22];
char vis[22][22];
int dir[4][2]={0,1,0,-1,1,0,-1,0};
void dfs(int x,int y){

    for(int i=0;i<4;i++){
        int xx=x+dir[i][0];
        int yy=y+dir[i][1];

        if(xx>=0&&xx<h&&yy>=0&&yy<w&&map[xx][yy]=='.'&&vis[xx][yy]==0){
            total++;
            vis[xx][yy]=1;
            dfs(xx,yy);

        }
    }
}
int main(){
    while(scanf("%d %d",&w,&h)){

        if(w==0&&h==0)break;

        total=0;

        getchar();

        for(int i=0;i<h;i++){
            for(int j=0;j<w;j++){
                scanf("%c",&map[i][j]);
                if(map[i][j]=='@'){s_x=i;s_y=j;map[i][j]='.';}

                vis[i][j]=0;
            }
            getchar();
        }

        vis[s_x][s_y]=1;
        total++;
        dfs(s_x,s_y);
        printf("%d\n",total);

    }

    return 0;
}
//不给初始点加访问标记的话,如果只有@一个点,直接走出去,为0
//所有这些都得先标记,避免当数很小的时候直接走出去而不进行计数自增操作
//也可以直接在dfs函数的第一行进行x,y访问标记。

第三题

1.奇偶剪枝
很简单的一个概念
设起点坐标是bx,by;终点坐标是ex,ey;
最短路径是abs(bx-ex)+abs(by-ey)
但是我们可以很显然的看出来,无论是走,我们的步数肯定比最短路径数多一个偶数
所以,简化的第一点来了:如果题目中输入的步数比最短路径数多得是一个奇数,那么我们永远也不可能走到,所以直接输出NO;
2.路径剪枝
在DFS当前的过程的路数中一旦大于等于要求的步数并且还没有找到终点,直接输出NO

&运算,
n&1就等价于n对2取余数,如果n为奇数,答案为1

Problem Description

The doggie found a bone in an ancient maze, which fascinated him a lot. However, when he picked it up, the maze began to shake, and the doggie could feel the ground sinking. He realized that the bone was a trap, and he tried desperately to get out of this maze.

The maze was a rectangle with sizes N by M. There was a door in the maze. At the beginning, the door was closed and it would open at the T-th second for a short period of time (less than 1 second). Therefore the doggie had to arrive at the door on exactly the T-th second. In every second, he could move one block to one of the upper, lower, left and right neighboring blocks. Once he entered a block, the ground of this block would start to sink and disappear in the next second. He could not stay at one block for more than one second, nor could he move into a visited block. Can the poor doggie survive? Please help him.

Input

The input consists of multiple test cases. The first line of each test case contains three integers N, M, and T (1 < N, M < 7; 0 < T < 50), which denote the sizes of the maze and the time at which the door will open, respectively. The next N lines give the maze layout, with each line containing M characters. A character is one of the following:

'X': a block of wall, which the doggie cannot enter;
'S': the start point of the doggie;
'D': the Door; or
'.': an empty block.

The input is terminated with three 0's. This test case is not to be processed.

Output

For each test case, print in one line "YES" if the doggie can survive, or "NO" otherwise.

Sample Input

4 4 5
S.X.
..X.
..XD
....
3 4 5
S.X.
..X.
...D
0 0 0

Sample Output
NO
YES

用dfs而非bfs,按理说,应该是求最短路径,但是题目是要求步数与时间刚刚好,而bfs做不到这个。
所以用dfs


ACcode


#include<iostream>
#include<cstdio>
#include<cmath>
#include<cstdlib>
using namespace std;
char maze[8][8];
int ma[8][8];
int s_x,s_y,e_x,e_y;
int n,m,t;
int dir[4][2]={1,0,-1,0,0,1,0,-1};
int flag=0;
int wall=0;
void dfs(int x,int y,int step){

    if(step==t&&e_x==x&&e_y==y){
        flag=1;
        return;
    }
    if(flag){
        return;
    }
    if(step>t){
        return;
    }
    //奇偶剪枝,目前所在的点到终点的距离与当前已走的点减去时间点比较
    int temp=abs(x-e_x)+abs(y-e_y)-abs(step-t);
    //如果是一个奇数,或者当要走的路大于应该走的步数的时候return
    if(temp>0||temp%2)return;
    //temp&1表示判断是偶数还是奇数

    for(int i=0;i<4;i++){
        int xx=x+dir[i][0];
        int yy=y+dir[i][1];

        if(xx>=0&&xx<n&&yy>=0&&yy<m&&ma[xx][yy]==1){
            ma[xx][yy]=0;
            dfs(xx,yy,step+1);
            //回溯!!!
            ma[xx][yy]=1;
        }
    }

//
}
int main(){
    while(cin>>n>>m>>t,(m+n+t)!=0){
        //注意初始
        wall=0;
        flag=0;
        getchar();
        for(int i=0;i<n;i++){
            for(int j=0;j<m;j++){
                char z;
                scanf("%c",&z);

                if(z=='.'){
                    ma[i][j]=1;
                }else if(z=='S'){
                    ma[i][j]=1;
                    s_x=i,s_y=j;
                }else if(z=='D'){
                    ma[i][j]=1;
                    e_x=i,e_y=j;
                }else{
                    ma[i][j]=0;
                    wall++;
                }

            }
            getchar();
        }
        
        //注意初始
        ma[s_x][s_y]=0;
        dfs(s_x,s_y,0);

        //输入问题,当输入的条件不可执行的时候输出no
        if(m*n-wall<t){
            printf("NO\n");
        }else{
            if(flag==1){
                printf("YES\n");
            }else{
                printf("NO\n");
            }
        }
    }
    return 0;
}

猜你喜欢

转载自www.cnblogs.com/Emcikem/p/11354158.html