1. 程式人生 > >HDOJ 1312題Red and Black

HDOJ 1312題Red and Black

Red and Black
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 13508 Accepted Submission(s): 8375

Problem Description
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
.#………
.#.#######.
.#.#…..#.
.#.#.###.#.
.#.#[email protected]#.#.
.#.#####.#.
.#…….#.
.#########.
………..
11 6
..#..#..#..
..#..#..#..
..#..#..###
..#..#..#@.
..#..#..#..
..#..#..#..
7 7
..#.#..
..#.#..

.

…@…

.

..#.#..
..#.#..
0 0

Sample Output
45
59
6
13

題意:
n*m的方陣有紅格或是黑格,只能走黑格
每次只能走上下左右四個緊鄰方向的格子,求
這個人最後能走多少個黑格子。

分析:
dfs水題。從第一個黑格子開始遞迴的搜尋,
每次搜尋一個黑格子後為了以後不再重複走
這個黑格子,就把當前搜尋的這個黑格子換
成紅格子,然後繼續dfs。。。

題目連結:http://acm.hdu.edu.cn/showproblem.php?pid=1312
題目大意:一個長方形空間,上面鋪紅色和黑色瓦片,一個人起初站在黑色瓦片上,每次可以走到相鄰的4個黑色瓦片上,輸入資料,求其能走過多少瓦片
題意:某人在@處為起點(也包括@點)#為牆,點(.)為通路,問最多能走多遠統計能走幾個點(加上@這個點)
思路:用dfs;
程式碼:

#include <stdio.h>
#include <stdlib.h>
#include<string.h>
char a[30][30];
int ss,n,m;//這3個值需要用全域性變數
int b[4][2]= {{0,-1},{0,1},{1,0},{-1,0}};
int dfs(int x,int y)
{
    int xx,yy;
    if(x<0||y<0||x>=m||y>=n)
        return 0;
    int i;
    for(i=0; i<4; i++)
    {
        xx=x+b[i][0];
        yy=y+b[i][1];
        if(xx<0||yy<0||xx>=m||yy>=n||a[xx][yy]=='#')
        //檢查該點上下左右的點是否符合題目要求。   
            continue;
        ss++;
        a[xx][yy]='#';
        //如果該點已經檢查過,就把它變成'#',防止再次被檢查。   
        dfs(xx,yy);
    }
}
int main()
{

    while(~scanf("%d%d",&n,&m)&&(n||m))//n,m不能同時為0
    {
        int i,j;
        int pi,pj;
        getchar();//吸收換行符。  
        for(i=0; i<m; i++)
        {
            for(j=0; j<n; j++)
            {
                scanf("%c",&a[i][j]);
                if(a[i][j]=='@')
                {
                    pi=i;
                    pj=j;
                }
            }
            getchar();//吸收換行符。   
        }
        a[pi][pj]='#';
        ss=1;
        dfs(pi,pj);
        printf("%d\n",ss);
    }
    return 0;
}