PoJ1979 Red and Black (DFS)

题目链接:http://poj.org/problem?id=1979

题意:

  有一个由正方形的黑色砖块和红色砖块组成的矩形广场,一个人站在广场上的某处,他可以选择往四周(上下左右)的黑色砖块上走,问他一共可以走多少个砖块(加上他本身站立的砖块).

  "."为黑色砖块

  "#"为红色砖块

  "@"为人的起始位置

思路:

  利用DFS 从人的起始位置开始搜索,搜索的过程中直接统计砖块的数量就好。

代码:

 1 #include <iostream>
 2 #include <cmath>
 3 #include <cstdio>
 4 #include <cstring>
 5 #include <cstdlib>
 6 #include <stack>
 7 #include <queue>
 8 #include <algorithm>
 9 #include <string>
10 
11 typedef long long LL;
12 using namespace std;
13 const double PI = acos(-1);
14 const int MAXN = 20;
15 int visit[MAXN + 3][MAXN + 3];//标记数组
16 char map[MAXN + 3][MAXN + 3];
17 int stepX[] = {-1, 0, 0, 1};
18 int stepY[] = {0, -1, 1, 0};
19 int cnt;
20 
21 void DFS(int x, int y) {
22     visit[x][y] = 1;
23     for(int i = 0; i < 4; i++) {
24         int tx = x + stepX[i], ty = y + stepY[i];
25         if(tx >=0 && ty >= 0 && !visit[tx][ty] && map[tx][ty] == '.'){
26             cnt++; //计数
27             visit[tx][ty] = 1;
28             DFS(tx, ty);
29         }
30     }
31 }
32 
33 int main() {
34     //freopen("input", "r", stdin);
35     int m = -1, h = -1;
36     while(scanf("%d%d", &m, &h), m || h) {
37         memset(visit, 0, sizeof(visit));
38         memset(map, 0, sizeof(map));
39         for(int i = 0; i < h; i++) scanf("%s", map[i]);
40         int stX = -1, stY = -1; //起始坐标
41         for(int i = 0; i < h; i++) {
42             for(int j = 0; j < m; j++) {
43                 if(map[i][j]== '@') stX = i, stY = j; 
44             }
45         }
46         cnt = 1;
47         DFS(stX, stY);//从起始坐标开始搜索
48         printf("%d
", cnt);
49     }
50     return 0;
51 }
原文地址:https://www.cnblogs.com/Ash-ly/p/5710597.html