【ACWing】1113. Red and Black

Subject address:

https://www.acwing.com/problem/content/1115/

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 WWW andHHH , respectivelyxxx- direction sumyyThe number of tiles in the y direction. In the nextHHIn line H , each line includesWWW characters. Each character represents the color of a tile. The rules are as follows:
(1).: black tile;
(2)#: red tile;
(3)@: black tile, and you stand 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 line 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 ≤ 20 1≤W, H≤201W,H20

Start DFS from the starting point and calculate it to @be at the same 4 44 communication block.number can. code show as below:

#include <iostream>
using namespace std;

const int N = 25, d[] = {
    
    1, 0, -1, 0, 1};
int n, m;
char g[N][N];
int res;

void dfs(int x, int y) {
    
    
    res++;
    g[x][y] = '#';
    for (int i = 0; i < 4; i++) {
    
    
        int nx = x + d[i], ny = y + d[i + 1];
        if (0 <= nx && nx < m && 0 <= ny && ny < n && g[nx][ny] == '.')
            dfs(nx, ny);
    }
}

int main() {
    
    
    while (1) {
    
    
        cin >> n >> m;
        if (n == 0 && m == 0) break;

        int x, y;
        for (int i = 0; i < m; i++) 
            for (int j = 0; j < n; j++) {
    
    
                cin >> g[i][j];
                if (g[i][j] == '@') x = i, y = j;
            }
        
        res = 0;
        dfs(x, y);
        cout << res << endl;
    }

    return 0;
}

Time and space complexity of each set of data O (nm) O (nm)O(nm)

Guess you like

Origin blog.csdn.net/qq_46105170/article/details/114813642