Skip to content

Instantly share code, notes, and snippets.

@taixingbi
Last active June 5, 2019 15:15
Show Gist options
  • Save taixingbi/da764a9851550f130fe52cc0433f79cc to your computer and use it in GitHub Desktop.
Save taixingbi/da764a9851550f130fe52cc0433f79cc to your computer and use it in GitHub Desktop.
class unionFindSet {
int[] parents;
unionFindSet(int n){
parents= new int[n];
for(int i=0; i<n; i++)
parents[i]= i;
}
//log(n)
//path compression
int find(int u){
while( u!= parents[u] ){
parents[u]= parents[ parents[u] ];
u= parents[u];
}
return u;
}
//weighted-union
boolean union(int u, int v){
int pu= find(u);
int pv= find(v);
if( pu==pv ) return false;
if(pu< pv) parents[pu]= pv;
else parents[pv]= pu;
return true;
}
}
200. Number of Islands
https://leetcode.com/problems/number-of-islands/
Given a 2d grid map of '1's (land) and '0's (water), count the number of islands. An island is surrounded by water and
is formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid are all
surrounded by water.
Example 1:
Input:
11110
11010
11000
00000
Output: 1
Example 2:
Input:
11000
11000
00100
00011
Output: 3
class unionFind {
int[] parents;
int cnt= 0;
unionFind(int n, int cnt){
parents= new int[n];
for(int i=0; i<n; i++)
parents[i]= i;
this.cnt= cnt;
}
int find(int u){
while( u!= parents[u] ){
parents[u]= parents[ parents[u] ];
u= parents[u];
}
return u;
}
boolean union(int u, int v){
int pu= find(u);
int pv= find(v);
if( pu==pv ) return false;
if(pu< pv) parents[pu]= pv;
else parents[pv]= pu;
cnt--;
return true;
}
}
class Solution {
int[][] dir= { {0,1}, {0,-1}, {1,0}, {-1,0} };
int m, n;
public int numIslands(char[][] grid) {
if(grid==null || grid.length==0) return 0;
m= grid.length;
n= grid[0].length;
int cnt= 0;
for(int i=0; i<m; i++){
for(int j=0; j<n; j++){
if( grid[i][j]=='1') cnt++;
}
}
unionFind uf= new unionFind(m*n, cnt);
for(int i=0; i<m; i++){
for(int j=0; j<n; j++){
if( grid[i][j]=='1'){
int u= i*n+j;
for(int[] d: dir){
int x= i+d[0], y= j+d[1];
if(x<0 || x>=m || y<0 || y>=n || grid[x][y]=='0' ) continue;
int v= x*n+y;
uf.union(u, v);
}
}
}
}
return uf.cnt;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment