LC 947. Most Stones Removed with Same Row or Column
On a 2D plane, we place stones at some integer coordinate points. Each coordinate point may have at most one stone.
Now, a move consists of removing a stone that shares a column or row with another stone on the grid.
What is the largest possible number of moves we can make?
Example 1:
Input: stones = [ [0,0],[0,1],[1,0],[1,2],[2,1],[2,2]] Output: 5 Example 2:
Input: stones = [ [0,0],[0,2],[1,1],[2,0],[2,2]] Output: 3 Example 3:
Input: stones = [ [0,0]] Output: 0
If we connect all stones with same column or row as an island, then this problem wants us to remove stones until there is only one stone left in this union. So in the result, #of islands = #of left stones. And the result = #of all stones - #of islands.
=>
This problem can be reversed to count the number of islands.
} intfind(int x){ if(x != regions[x]) regions[x] = find(regions[x]); return regions[x]; } voiduni(int x, int y){ int xroot = find(x); int yroot = find(y); if(xroot != yroot){ regions[xroot] = yroot; islands--; } } intg(int i, int j, int k){ return (i*n + j) * 4 + k; } };
323. Number of Connected Components in an Undirected Graph
Given n nodes labeled from 0 to n - 1 and a list of undirected edges (each edge is a pair of nodes), write a function to find the number of connected components in an undirected graph.
Example 1:
Input: n = 5 and edges = [[0, 1], [1, 2], [3, 4]]
0 3
| |
1 --- 2 4
Output: 2
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
intfind(int x, vector<int> roots){ if(x != roots[x]) roots[x] = find(roots[x], roots); return roots[x]; } intcountComponents(int n, vector<pair<int, int>>& edges){ vector<int> roots(n, 0); for(int i = 0; i < n; i++) roots[i] = i; for(auto p : edges){ int sroot = find(p.first, roots); int eroot = find(p.second, roots); if(sroot != eroot){ roots[sroot] = eroot; n--; } } return n; }
近期评论