zoukankan      html  css  js  c++  java
  • HDU 1312.Red and Black-DFS

    Red and Black

    Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)
    Total Submission(s): 19690    Accepted Submission(s): 11965


    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
    Sample Output
    45
    59
    6
    13
     
     
     
     
    代码:
     1 #include<bits/stdc++.h>
     2 using namespace std;
     3 int direct [4][2]={-1,0,1,0,0,1,0,-1};
     4 char str[25][25];
     5 bool flag[25][25];
     6 int w,h,ans;
     7 void DFS(int x,int y){
     8     for(int i=0;i<4;i++){
     9         int p=x+direct[i][0];
    10         int q=y+direct[i][1];
    11         if(p>=0&&p<h&&q>=0&&q<w&&flag[p][q]==0&&str[p][q]=='.'){
    12             ans++;
    13             flag[p][q]=1;
    14             DFS(p,q);
    15         }
    16     }
    17 }
    18 int main(){
    19     int Dx,Dy;
    20     while(~scanf("%d%d",&w,&h)){
    21         if(w==0&&h==0)break;
    22         memset(flag,0,sizeof(flag));
    23         getchar();
    24         for(int i=0;i<h;i++){
    25             for(int j=0;j<w;j++){
    26                 scanf("%c",&str[i][j]);
    27                 if(str[i][j]=='@'){
    28                     Dx=i;
    29                     Dy=j;
    30                 }
    31             }getchar();
    32         }
    33         ans=1;
    34         flag[Dx][Dy]=1;
    35         DFS(Dx,Dy);
    36         printf("%d
    ",ans);
    37     }
    38     return 0;
    39 }
  • 相关阅读:
    求数列的和
    统计字符
    保留最大的数
    POJ百练—IP地址转换
    HDOJ1213(并查集)
    HDOJ1059(多重背包)
    HDOJ1171(多重背包)
    多重背包(标准模板)
    HDOJ1251(前缀匹配---分块查找&map应用)
    hdoj1113(字符串map应用)
  • 原文地址:https://www.cnblogs.com/ZERO-/p/6665668.html
Copyright © 2011-2022 走看看