题目: https://leetcode.cn/problems/regions-cut-by-slashes/description/
题解(参考了讨论区):将初始N*N的网格看做4 * N* N的三角形集合,根据输入合并对应的三角形。
C# 实现
public class Solution { public int RegionsBySlashes(string[] grid) { UnionFind uf = new UnionFind(4 * grid.Length * grid.Length); for (int i = 0; i < grid.Length; i++) { for (int j = 0; j < grid.Length; j++) { int start = 4 * (i * grid.Length + j); switch (grid[i][j]) { case ' ': uf.Union(start, start + 1); uf.Union(start + 2, start + 3); uf.Union(start, start + 2); break; case '/': uf.Union(start, start + 3); uf.Union(start + 1, start + 2); break; case '\\': uf.Union(start, start + 1); uf.Union(start + 2, start + 3); break; } if (i > 0) { uf.Union(start, start - 4 * grid.Length + 2); } if (j > 0) { uf.Union(start + 3, start - 3); } } } return uf.GetGroups(); }
//该实现采用了路径压缩算法,以保证最坏情况下合并操作的成本小于logN public class UnionFind { private int[] uf; private int[] ufSize; public UnionFind(int N) { uf = new int[N]; ufSize = new int[N]; for (int i = 0; i < N; i++) { uf[i] = i; ufSize[i] = 1; } } public int Find(int p) { int root = p; while (root != uf[root]) { root = uf[root]; } while (p != root) { int newP = uf[p]; uf[p] = root; p = newP; } return root; } public void Union(int p, int q) { int pRoot = Find(p); int qRoot = Find(q); if (pRoot != qRoot) { if (ufSize[pRoot] > ufSize[qRoot]) { uf[qRoot] = pRoot; ufSize[pRoot] += ufSize[qRoot]; } else { uf[pRoot] = qRoot; ufSize[qRoot] += ufSize[pRoot]; } } } public int GetGroups() { int count = 0; for (int i = 0; i < uf.Length; i++) { if (uf[i] == i) count++; } return count; } } }
标签:959,int,Union,start,grid,斜杠,uf,LeetCode,ufSize From: https://www.cnblogs.com/ayang1/p/17303124.html