Gym 102423I

Maze Connect

The meaning of the question is to determine how many edges are removed at least, the graph becomes all connected, in fact, it is to find how many connected blocks there are, and just run it with dfs.
The difficulty lies in turning \ / into the shape corresponding to the 2 * 2 square, because these two signs have directions.

The method of dfs to find connected blocks is to traverse all positions, find the ones that are not walls, and enter dfs, and mark all the ones that are not walls to avoid repeated recording next time, so as to ensure that every connected block has an empty space to be recorded once. Subtract 1 from the calculated value.

#include <algorithm>
#include <bitset>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <deque>
#include <functional>
#include <iostream>
#include <map>
#include <queue>
#include <set>
#include <stack>
#include <string>
#include <vector>
using namespace std;
int c, r;
char mp[1010][1010];
bool vis[2500][2500];
bool book[2500][2500];
int l[4] = {
    
    -1, 0, 0, 1};
int t[4] = {
    
    0, -1, 1, 0};

void dfs(int x, int y) {
    
    
    int i, tx, ty;
    vis[x][y] = 1;
    for (i = 0; i < 4; i++) {
    
    
        tx = x + l[i];
        ty = y + t[i];
        if (book[tx][ty]) continue;
        if (vis[tx][ty]) continue;
        if (tx < 0 || ty < 0 || tx > c || ty > r) continue;
        dfs(tx, ty);
    }
    return;
}

int main(int argc, char const *argv[]) {
    
    
    int n, m, i, j, sum = 0;
    scanf("%d%d", &n, &m);
    for (i = 1; i <= n; i++) {
    
    
        getchar();
        for (j = 1; j <= m; j++) scanf("%c", &mp[i][j]);
    }
    for (i = 1; i <= n; i++) {
    
    
        for (j = 1; j <= m; j++) {
    
    
            if (mp[i][j] == '/') {
    
    
                book[i * 2][j * 2 + 1] = 1;
                book[i * 2 + 1][j * 2] = 1;
            } else if (mp[i][j] == '\\') {
    
    
                book[i * 2][j * 2] = 1;
                book[i * 2 + 1][j * 2 + 1] = 1;
            }
        }
    }
    c = n * 2 + 5;
    r = m * 2 + 5;
    for (i = 0; i <= c; i++)
        for (j = 0; j <= r; j++)
            if (vis[i][j] == 0 && book[i][j] == 0) {
    
    
                sum++;
                dfs(i, j);
            }
    printf("%d\n", sum - 1);
    return 0;
}

Guess you like

Origin blog.csdn.net/qq_47783181/article/details/112978825