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

Sample Input

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

Sample Output

45
59
6
13

描述:英文题看似长,其实就是让你找一下从@符号开始有多少个连续的‘.’,注意不能穿过“#”。。。

由于今天刚刚接触DFS有点生,加深一下印象吧。

必须明白的点:

  1. 如何表示移动的方向;
  2. 使用过的数组必须清空;
  3. 区分DFS与BFS的异同;

 对于方向问题可以定义一个二维数组控制通过变量的改变来控制点的移动;

清空数组记得用memset函数。不然代价就是wa3次;

编译器中定义0x3f3f3f3f可以 令int数字在int范围内取得最大值。

另外无意中发现全局变量的优点,即使在函数中也可以使用。不实践怕是永远也无法得知的,小白一个,,加油吧。

贴代码吧。。。

#include<bits/stdc++.h>
using namespace std;
#define ll long long
const int MAXN=0x3f3f3f3f;
const int N=40;
char str[N][N];
int r[N][N];
int a,b,sum;
int fab[2][4]={{0,1,0,-1},{1,0,-1,0}};//控制方向
bool check(int i,int j){
    if(i<0||i>=b||j<0||j>=a||str[i][j]=='#'){
        return 0;//确保i,j不越界
    }
    else return 1;
}
void DFS(int i,int j){
    if(!check(i,j)||r[i][j]){
        return ;//检查输入数据的合理性
    }
    else{
        int fx,fy;

        for(int k=0;k<4;k++){
            r[i][j]=1;
            fx=i+fab[0][k];
            fy=j+fab[1][k];//寻找周围的点
            DFS(fx,fy);//递归
        }
        sum++;
    }
}
int main(){
    while(scanf("%d%d",&a,&b)!=EOF&&(a||b)){
        memset(str,0,sizeof(str));
        memset(r,0,sizeof(r));
        for(int i=0;i<b;i++){
            scanf("%s",&str[i]);
        }
        sum=0;
        for(int i=0;i<b;i++){
            for(int j=0;j<a;j++){
                if(str[i][j]=='@'){
                    DFS(i,j);//遍历寻找"@"的位置
                    break;
                }
            }
        }
        printf("%d\n",sum);
    }
    return 0;
}

加油!有一个好的开始!以此自励!

猜你喜欢

转载自blog.csdn.net/liubang00001/article/details/81334472