Skip to content

Instantly share code, notes, and snippets.

@rajeakshay
Last active September 18, 2016 12:14
Show Gist options
  • Save rajeakshay/90d16aec0f577201a4b0d399e4d04781 to your computer and use it in GitHub Desktop.
Save rajeakshay/90d16aec0f577201a4b0d399e4d04781 to your computer and use it in GitHub Desktop.
LeetCode 200. Number of Islands - (Problem Link: 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 b…
/**
*
LeetCode 200. 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:
11110
11010
11000
00000
Answer: 1
Example 2:
11000
11000
00100
00011
Answer: 3
* */
public class NumberOfIslands {
static class Pair{
int row;
int col;
Pair(int x, int y){
row = x;
col = y;
}
}
public void dfs(char[][] grid, boolean[][] visited, int row, int col){
int[] dx = {0, 0, -1, 1};
int[] dy = {-1, 1, 0, 0};
Deque<Pair> stack = new ArrayDeque<Pair>();
stack.push(new Pair(row,col));
while(!stack.isEmpty()){
Pair current = stack.pop();
visited[current.row][current.col] = true;
for(int k = 0; k < 4; k++){
int newRow = current.row + dx[k];
int newCol = current.col + dy[k];
if(newRow >= 0 && newRow <= grid.length - 1 &&
newCol >= 0 && newCol <= grid[0].length - 1){
if(grid[newRow][newCol] == '1' && !visited[newRow][newCol]){
stack.push(new Pair(newRow, newCol));
visited[newRow][newCol] = true;
}
}
}
}
}
public int numIslands(char[][] grid) {
if(grid.length == 0) return 0;
boolean[][] visited = new boolean[grid.length][grid[0].length];
int noOfIslands = 0;
for(int row = 0; row < grid.length; row++){
for(int col = 0; col < grid[0].length; col++){
if(grid[row][col] == '1' && !visited[row][col]){
dfs(grid, visited, row, col);
noOfIslands++;
}
}
}
return noOfIslands;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment