1. 程式人生 > 其它 >LeetCode 959 由斜槓劃分區域 HERODING的LeetCode之路

LeetCode 959 由斜槓劃分區域 HERODING的LeetCode之路

技術標籤:LeetCodeleetcode資料結構c++演算法並查集

在由 1 x 1 方格組成的 N x N 網格 grid 中,每個 1 x 1 方塊由 /、\ 或空格構成。這些字元會將方塊劃分為一些共邊的區域。

(請注意,反斜槓字元是轉義的,因此 \ 用 “\” 表示。)。

返回區域的數目。

示例 1:
在這裡插入圖片描述

輸入:
[
" /",
"/ "
]
輸出:2
解釋:2x2 網格如下:

示例 2:
在這裡插入圖片描述

輸入:
[
" /",
" "
]
輸出:1
解釋:2x2 網格如下:

示例 3:
在這裡插入圖片描述

輸入:
[
“\/”,
“/\”
]

輸出:4
解釋:(回想一下,因為 \ 字元是轉義的,所以 “\/” 表示 /,而 “/\” 表示 /\。)
2x2 網格如下:

示例 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

著作權歸領釦網路所有。商業轉載請聯絡官方授權,非商業轉載請註明出處。

解題思路:
又是並查集的知識。。。這個月還真是並查集月,這道題目思路還是很簡單的,就是把方格聯想成四個點組合成的一個模組,那麼分成的各個區域就是不同的點並查集的集合的個數,關鍵點在於合併的思考,詳細的注意要點在官方題解中有說明,這裡不過多贅述,程式碼如下:

class Solution {
public:
    int find(vector<int>& f, int x) {
        if (f[x] == x) {
            return x;
        }
        int
fa = find(f, f[x]); f[x] = fa; return fa; } void merge(vector<int>& f, int x, int y) { int fx = find(f, x); int fy = find(f, y); f[fx] = fy; } int regionsBySlashes(vector<string>& grid) { int n = grid.size(); vector<int> f(n * n * 4); for (int i = 0; i < n * n * 4; i++) { f[i] = i; } 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; merge(f, idx * 4 + 2, bottom * 4); } if (j < n - 1) { int right = idx + 1; merge(f, idx * 4 + 1, right * 4 + 3); } if (grid[i][j] == '/') { merge(f, idx * 4, idx * 4 + 3); merge(f, idx * 4 + 1, idx * 4 + 2); } else if (grid[i][j] == '\\') { merge(f, idx * 4, idx * 4 + 1); merge(f, idx * 4 + 2, idx * 4 + 3); } else { merge(f, idx * 4, idx * 4 + 1); merge(f, idx * 4 + 1, idx * 4 + 2); merge(f, idx * 4 + 2, idx * 4 + 3); } } } unordered_set<int> fathers; for (int i = 0; i < n * n * 4; i++) { int fa = find(f, i); fathers.insert(fa); } return fathers.size(); } };