LeetCode:959. Regions Cut By Slashes由斜槓劃分區域(C語言)
阿新 • • 發佈:2021-01-26
技術標籤:LeetCode
題目描述:
在由 1 x 1 方格組成的 N x N 網格 grid 中,每個 1 x 1 方塊由 /、\ 或空格構成。這些字元會將方塊劃分為一些共邊的區域。
(請注意,反斜槓字元是轉義的,因此 \ 用 “\” 表示。)。
返回區域的數目。
示例 1:
輸入:
[
" /",
"/ "
]
輸出:2
解釋:2x2 網格如下:
示例 2:
輸入:
[
" /",
" "
]
輸出:1
解釋:2x2 網格如下:
示例 3:
輸入:
[
“\/”,
“/\”
]
輸出:4
解釋:(回想一下,因為 \ 字元是轉義的,所以 “\/” 表示 /,而 “/\” 表示 /\。)
示例 4:
輸入:
[
“/\”,
“\/”
]
輸出:5
解釋:(回想一下,因為 \ 字元是轉義的,所以 “/\” 表示 /\,而 “\/” 表示 /。)
2x2 網格如下:
示例 5:
輸入:
[
“//”,
"/ "
]
輸出:3
解釋:2x2 網格如下:
提示:
1 <= grid.length == grid[0].length <= 30
grid[i][j] 是 '/'、'\'、或 ' '。
來源:力扣(LeetCode)
連結:https://leetcode-cn.com/problems/regions-cut-by-slashes
著作權歸領釦網路所有。商業轉載請聯絡官方授權,非商業轉載請註明出處。
void swap(int* a, int* b) {
int tmp = *a;
*a = *b, *b = tmp;
}
struct DisjointSetUnion {
int *f, *size;
int n, setCount;
};
void initDSU(struct DisjointSetUnion* obj, int n) {
obj->f = malloc(sizeof(int) * n);
obj->size = malloc(sizeof(int) * n);
obj->n = n;
obj->setCount = n;
for (int i = 0; i < n; i++) {
obj->f[i] = i;
obj->size[i] = 1;
}
}
int find(struct DisjointSetUnion* obj, int x) {
return obj->f[x] == x ? x : (obj->f[x] = find(obj, obj->f[x]));
}
int unionSet(struct DisjointSetUnion* obj, int x, int y) {
int fx = find(obj, x), fy = find(obj, y);
if (fx == fy) {
return false;
}
if (obj->size[fx] < obj->size[fy]) {
swap(&fx, &fy);
}
obj->size[fx] += obj->size[fy];
obj->f[fy] = fx;
obj->setCount--;
return true;
}
struct HashTable {
int val;
UT_hash_handle hh;
};
int regionsBySlashes(char** grid, int gridSize) {
int n = gridSize;
struct DisjointSetUnion* uf = malloc(sizeof(struct DisjointSetUnion));
initDSU(uf, n * n * 4);
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
int idx = i * n + j;
if (i < n - 1) {
int bottom = idx + n;
unionSet(uf, idx * 4 + 2, bottom * 4);
}
if (j < n - 1) {
int right = idx + 1;
unionSet(uf, idx * 4 + 1, right * 4 + 3);
}
if (grid[i][j] == '/') {
unionSet(uf, idx * 4, idx * 4 + 3);
unionSet(uf, idx * 4 + 1, idx * 4 + 2);
} else if (grid[i][j] == '\\') {
unionSet(uf, idx * 4, idx * 4 + 1);
unionSet(uf, idx * 4 + 2, idx * 4 + 3);
} else {
unionSet(uf, idx * 4, idx * 4 + 1);
unionSet(uf, idx * 4 + 1, idx * 4 + 2);
unionSet(uf, idx * 4 + 2, idx * 4 + 3);
}
}
}
struct HashTable* fathers = NULL;
for (int i = 0; i < n * n * 4; i++) {
int fa = find(uf, i);
struct HashTable* tmp;
HASH_FIND_INT(fathers, &fa, tmp);
if (tmp == NULL) {
tmp = malloc(sizeof(struct HashTable));
tmp->val = fa;
HASH_ADD_INT(fathers, val, tmp);
}
}
return HASH_COUNT(fathers);
}
執行結果:
Notes:
參考官方文件:https://leetcode-cn.com/problems/regions-cut-by-slashes/solution/you-xie-gang-hua-fen-qu-yu-by-leetcode-s-ztob/