Maze Connect
题意是判断最少将多少条边去掉之后,该图变成全部连通,其实就是找有多少个连通块,用dfs跑一下就过了。
难点在于把\ /变成2 * 2的方格对应的形状,因为这两个符号带有方向。
dfs找连通块的方法就是遍历所有位置,找到不是墙的就dfs进去,将所有不是墙的都标记上,避免下次重复记录,这样就可以保证每一个连通块都有一个空地被记录一次,求出来的再减去1。
#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;
}