zoukankan      html  css  js  c++  java
  • poj 1979 Red and Black

    题目大意:

      一块地为矩形,分成许多瓷砖。你站在一块黑色瓷砖上,只能走到周围相连的黑瓷砖上,问你总共能走过多少块瓷砖?(包括你最初站立的那块瓷砖)

    Sample Input

    6 9
    ....#.
    .....#
    ......
    ......
    ......
    ......
    ......
    #@...#
    .#..#.
    11 9
    .#.........
    .#.#######.
    .#.#.....#.
    .#.#.###.#.
    .#.#..@#.#.
    .#.#####.#.
    .#.......#.
    .#########.
    ...........
    11 6
    ..#..#..#..
    ..#..#..#..
    ..#..#..###
    ..#..#..#@.
    ..#..#..#..
    ..#..#..#..
    7 7
    ..#.#..
    ..#.#..
    ###.###
    ...@...
    ###.###
    ..#.#..
    ..#.#..
    0 0
    (@为你站立的位置,.为黑瓷砖,#为其他)

    Sample Output

    45
    59
    6
    13

    简单的深度优先搜索题,代码如下
     1 #include <cstdio>
     2 #include <cstdlib>
     3 #include <cstring>
     4 
     5 int dir[][2] = {{0,1}, {0,-1},{-1,0},{1,0}};
     6 int w, h;
     7 
     8 char tiles[22][22];
     9 int flag[22][22];
    10 int ans;
    11 void dfs(int x, int y) {
    12     for(int i = 0; i < 4; i++) {
    13         int tpx = x + dir[i][0];
    14         int tpy = y + dir[i][1];
    15         if(tpx >= 0 && tpy >= 0 && tpx < h && tpy < w && flag[tpx][tpy] == 0 && tiles[tpx][tpy] == '.') {
    16             flag[tpx][tpy] = 1;    
    17             ans++;
    18             dfs(tpx, tpy);
    19         }
    20     }
    21 }
    22 int main(int argc, char const *argv[])
    23 {
    24     freopen("input.txt","r",stdin);
    25     while(scanf("%d %d",&w, &h) != EOF && (w != 0 && h != 0)) {
    26         for(int i = 0; i < h; i++) {
    27             scanf("%s",tiles[i]);
    28         }
    29         int x0, y0;
    30         for(int i = 0; i < h; i++) {
    31             for(int j = 0; j < w; j++) {
    32                 if(tiles[i][j] == '@') {
    33                     x0 = i, y0 = j;
    34                     break;
    35                 }
    36             }
    37         }
    38         memset(flag, 0, sizeof(flag));
    39         ans = 1;
    40         flag[x0][y0] = 1;
    41         dfs(x0, y0);
    42         printf("%d
    ",ans);
    43     }
    44     return 0;
    45 }
  • 相关阅读:
    matrix
    meizi
    公文流转系统
    10.21连接数据库进行添加
    9.27
    9.23课堂总结
    信息管理java
    大道至简读后感
    第二周
    7.7第一周
  • 原文地址:https://www.cnblogs.com/jasonJie/p/5800890.html
Copyright © 2011-2022 走看看