Skip to content

Instantly share code, notes, and snippets.

@cangoal
Last active August 29, 2015 14:22
Show Gist options
  • Save cangoal/7baab7e0f68a84752330 to your computer and use it in GitHub Desktop.
Save cangoal/7baab7e0f68a84752330 to your computer and use it in GitHub Desktop.
LeetCode - Number of Islands
// BFS ---> note: this my cause issue when you encode the coordinates
public int numIslands(char[][] grid) {
if(grid==null || grid.length==0) return 0;
int count = 0;
for(int i=0; i<grid.length; i++){
for(int j=0; j<grid[0].length; j++){
if(grid[i][j] == '1'){
count++;
setZeros(grid, i, j);
}
}
}
return count;
}
public void setZeros(char[][] grid, int x, int y){
grid[x][y] = '0';
Queue<Integer> queue = new LinkedList<Integer>();
queue.offer(x*grid[0].length + y);
while(!queue.isEmpty()){
int cor = queue.poll();
int row = cor / grid[0].length;
int col = cor % grid[0].length;
grid[row][col] = '0';
if(row-1 >= 0 && grid[row-1][col] == '1'){
queue.offer((row-1) * grid[0].length + col);
grid[row-1][col] = '0';
}
if(row+1 < grid.length && grid[row+1][col] == '1'){
queue.offer((row+1) * grid[0].length + col);
grid[row+1][col] = '0';
}
if(col-1 >= 0 && grid[row][col-1] == '1'){
queue.offer(row * grid[0].length + col-1);
grid[row][col-1] = '0';
}
if(col+1 < grid[0].length && grid[row][col+1] == '1'){
queue.offer(row * grid[0].length + col+1);
grid[row][col+1] = '0';
}
}
}
// DFS
public int numIslands(char[][] grid) {
int ret = 0;
if(grid == null || grid.length == 0 || grid[0].length == 0) return ret;
for(int i=0; i<grid.length; i++){
for(int j=0; j<grid[0].length; j++){
if(grid[i][j] == '1'){
ret++;
helper(i,j, grid);
}
}
}
return ret;
}
public void helper(int x, int y, char[][] grid){
if(x<0 || y<0 || x>=grid.length || y>=grid[0].length) return;
if(grid[x][y] == '1'){
grid[x][y] = '0';
helper(x-1, y, grid);
helper(x, y-1, grid);
helper(x+1, y, grid);
helper(x, y+1, grid);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment