生活随笔
收集整理的這篇文章主要介紹了
并查集 - 由斜杠划分区域
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
題目鏈接
求劃分區域的個數,也就是求連通分量的個數,將每個單元格劃分為4個部分,分別根據空格、斜杠、反斜杠進行合并。
單元格之間也要合并,上下、左右各選一個方向即可。
class UnionFind{public:UnionFind(int n
): count(n
), parent(n
), size(n
, 1) {iota(parent
.begin(), parent
.end(), 0);}int find(int x
) {return x
== parent
[x
] ? x
: find(parent
[x
]);}bool unite(int x
, int y
) {x
= find(x
);y
= find(y
);if (x
== y
) {return false;}if (size
[x
] < size
[y
]) {swap(x
, y
);}parent
[y
] = x
;size
[x
] += size
[y
];--count
; return true;}public:int count
;vector
<int> parent
;vector
<int> size
;
};class Solution {
public:int regionsBySlashes(vector
<string
>& grid
) {int n
= grid
.size();UnionFind
uf(4 * n
* n
);for (int i
= 0; i
< n
; ++i
) {for (int j
= 0; j
< n
; ++j
) {int idx
= (i
* n
+ j
) * 4;if (grid
[i
][j
] == ' ') { uf
.unite(idx
, idx
+1);uf
.unite(idx
+1, idx
+2);uf
.unite(idx
+2, idx
+3);}else if (grid
[i
][j
] == '/') { uf
.unite(idx
, idx
+3);uf
.unite(idx
+1, idx
+2);}else { uf
.unite(idx
, idx
+1);uf
.unite(idx
+2, idx
+3);}if (j
+ 1 < n
) {uf
.unite(idx
+1, idx
+7);}if (i
+ 1 < n
) {uf
.unite(idx
+2, idx
+n
*4);}}}return uf
.count
;}
};
總結
以上是生活随笔為你收集整理的并查集 - 由斜杠划分区域的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。