红与黑(DFS)

描述有一间长方形的房子,地上铺了红色、黑色两种颜色的正方形瓷砖。你站在其中一块黑色的瓷砖上,只能向相邻的黑色瓷砖移动。请写一个程序,计算你总共能够到达多少块黑色的瓷砖。输入包括多个数据集合。每个数据集合的第一行是两个整数W和H,分别表示x方向和y方向瓷砖的数量。W和H都不超过20。在接下来的H行中,每行包括W个字符。每个字符表示一块瓷砖的颜色,规则如下
1)‘.’:黑色的瓷砖;
2)‘#’:白色的瓷砖;
3)‘@’:黑色的瓷砖,并且你站在这块瓷砖上。该字符在每个数据集合中唯一出现一次。
当在一行中读入的是两个零时,表示输入结束。
输出对每个数据集合,分别输出一行,显示你从初始位置出发能到达的瓷砖数(记数时包括初始位置的瓷砖)。样例输入

6 9 
....#. 
.....# 
...... 
...... 
...... 
...... 
...... 
#@...# 
.#..#. 
0 0

样例输出

45

来源1979

一道简单的DFS,在这道题中应该注意是四个方向搜索,还有两从循环的跳出

#include <iostream>      
using namespace std;

// 题目中给出的最大宽度和高度
#define MAX_W 20
#define MAX_H 20

// 待输入的宽度和高度以及已走的步数
int W, H;     
int step = 0;

// 待写入的二维数组
char room[MAX_W][MAX_H];
// 顺时针的可走方向
const int direc[4][2] = {
    {0, -1},
    {1,0},
    {0, 1},
    {-1 ,0},
};				
//4个方向 


int dfs(const int& row, const int& col) {
    // 走过的点		这个地方用了取地址符号 
    room[row][col] = '#';
    // 计算步数
    ++step;
    for (int d = 0; d < 4; ++d) {
        int curRow = row + direc[d][1];
        int curCol = col + direc[d][0];
        if (curRow >= 0 && curRow < H && curCol >= 0 && curCol < W && room[curRow][curCol] == '.') {
            dfs(curRow, curCol);
        }
    }
    return step;
}

int main()
{
    bool found;
    while (cin >> W >> H, W > 0) {
        step = 0;
        int col, row;
        // 输入
        for (row = 0; row < H; ++row) {
            for (col = 0; col < W; ++col) {
                cin >> room[row][col];
            }
        }
        found = false;
        // 找到起始点
        for (row = 0; row < H; ++row) {
            for (col = 0; col < W; ++col) {
                if (room[row][col] == '@') {
                    found = true;
                    break;
                }
            }
            if (found) {
                break;		//	两个for循环的跳出方法 
            }                   
        }
        // 开始搜索
        cout << dfs(row, col) << endl;
    }
}

  

永远渴望,大智若愚(stay hungry, stay foolish)
原文地址:https://www.cnblogs.com/h-hkai/p/7441535.html