leetcode-并查集
-
题目:130
并查集:
class Solution: def solve(self, board: List[List[str]]) -> None: """ Do not return anything, modify board in-place instead. """ f = {} def find(x): f.setdefault(x,x) if f[x]!=x: f[x] = find(f[x]) return f[x] def union(x,y): f[find(y)] = find(x) if not board or not board[0]: return row,col = len(board),len(board[0]) dummy = row*col for i in range(row): for j in range(col): if board[i][j] == "O": if i == 0 or i == row - 1 or j == 0 or j == col - 1: union(i * col + j, dummy) else: for x, y in [(-1, 0), (1, 0), (0, -1), (0, 1)]: if board[i + x][j + y] == "O": union(i * col + j, (i + x) * col + (j + y)) for i in range(row): for j in range(col): if find(dummy) == find(i * col + j): board[i][j] = "O" else: board[i][j] = "X"
题200:
并查集
class Solution: def numIslands(self, grid: List[List[str]]) -> int: f = {} def find(x): f.setdefault(x,x) if f[x]!=x: f[x] = find(f[x]) return f[x] def union(x,y): f[find(y)] = find(x) if not grid: return 0 row,col =len(grid),len(grid[0]) for i in range(row): for j in range(col): if grid[i][j] == "1": for x, y in [[-1, 0], [0, -1]]: tmp_i = i + x tmp_j = j + y if 0 <= tmp_i < row and 0 <= tmp_j < col and grid[tmp_i][tmp_j] == "1": union(tmp_i * col + tmp_j, i * col + j) res = set() for i in range(row): for j in range(col): if grid[i][j] == "1": res.add(find(col*i+j)) return len(res)
题目684:
方法:并查集 O(N) O(N)
from collections import defaultdict class Solution: def findRedundantConnection(self, edges: List[List[int]]) -> List[int]: f = {} def find(x): f.setdefault(x,x) if f[x] != x: f[x] = find(f[x]) return f[x] def union(x,y): if find(x) != find(y): f[find(y)] = find(x) for x,y in edges: if find(x) == find(y): return [x,y] else: union(x,y)
另:
class Solution: def findRedundantConnection(self, edges: List[List[int]]) -> List[int]: p = {i: {i} for i in range(1, len(edges) + 1)} #并查集初始化 for x, y in edges: if p[x] is not p[y]: #如果两个集合地址不一样 p[x] |= p[y] #合并集合 for z in p[y]: p[z] = p[x] #修改元素集合标记的指针地址 else: return [x, y]
题685
并查集;
class Solution: def findRedundantDirectedConnection(self, edges: List[List[int]]) -> List[int]: def find(f,x): f.setdefault(x,x) if f[x] != x: f[x] = find(f,f[x]) return f[x] def cycle(graph): f = {} for x,y in graph: if find(f,x) == find(f,y): return True else: f[find(f,y)] = find(f,x) indegree = {i:0 for i in range(1,len(edges)+1)} tmp = 0 for i,j in edges: indegree[j] += 1 if indegree[j] == 2: tmp = j break if tmp == 0: f = {} for x,y in edges: if find(f,x) == find(f,y): return [x,y] else: f[find(f,y)] = find(f,x) else: for x,y in edges[::-1]: if y == tmp: if not cycle(edges[:edges.index([x,y])]+edges[edges.index([x,y])+1:]) : return [x,y]