ACwing 1113 red and black

Title description:
 

There is a rectangular house with square tiles in red and black on the floor.

You stand on one of the black tiles and can only move to the adjacent black tiles (up, down, left, and right).

Please write a program to calculate how many black tiles you can reach in total.

Input format

The input includes multiple data sets.

The first row of each data set is two integers WW and HH, which represent the number of tiles in the xx direction and yy direction, respectively.

In the following HH lines, each line contains WW characters. Each character represents the color of a tile, the rules are as follows

1)'.': black tiles;
2)'#': red tiles;
3)'@': black tiles, and you are standing on this tile. This character appears only once in each data set.

When two zeros are read in a row, it means that the input is over.

Output format

For each data set, output a row separately, showing the number of tiles you can reach from the initial position (including the tiles at the initial position when counting).

data range

1≤W,H≤201≤W,H≤20

Input sample:

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

Sample output:

45

 Classic deep search

#include <iostream>
#include <cstdio>

using namespace std;
const int MAX = 25;

char a[MAX][MAX];
int dirx[4] = {-1, 1, 0, 0};
int diry[4] = {0, 0, -1, 1};
int n, m;

int cnt;

void dfs(int x, int y)
{
    a[x][y] = '#';
    for(int i = 0; i < 4; i++)
    {
        int nx = x + dirx[i];
        int ny = y + diry[i];
        if(nx >= 0 && nx < n && ny >= 0 && ny < m && a[nx][ny] == '.')
        {
            cnt++;
            dfs(nx, ny);
        }
    }
}

int main()
{
    while(scanf("%d%d", &m, &n))
    {
        if(n == 0 && m == 0)
            break;

        for(int i = 0; i < n; i++)
        {
            scanf(" %s",a[i]);
        }


        bool f = false;
        cnt = 1;

        for(int i = 0; i < n; i++)
        {

            for(int j = 0; j < m; j++)
            {
               if(a[i][j] == '@')
               {
                   dfs(i, j);
                   f = true;
                   break;
               }
            }
            if(f)
                break;
        }

        printf("%d\n", cnt);

    }
    return 0;
}

 

Guess you like

Origin blog.csdn.net/weixin_44620183/article/details/112971204