Skip to content

Instantly share code, notes, and snippets.

@InterviewBytes
Created June 6, 2017 15:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save InterviewBytes/ae85e1afce451fb4437de3a9af6107e8 to your computer and use it in GitHub Desktop.
Save InterviewBytes/ae85e1afce451fb4437de3a9af6107e8 to your computer and use it in GitHub Desktop.
Number of Islands problem.
package com.interviewbytes.islands;
public class Solution {
public int numIslands(char[][] grid) {
if(grid == null || grid.length == 0) return 0;
final int M = grid.length;
final int N = grid[0].length;
boolean visited[][] = new boolean[M][N];
int islandCount = 0;
for (int i = 0; i < M; i++) {
for (int j = 0; j < N; j++) {
if (!visited[i][j] && grid[i][j] == '1') {
dfs(grid, visited, i, j, M, N);
islandCount++;
}
}
}
return islandCount;
}
private void dfs(char[][] grid, boolean[][] visited, int i, int j, int m, int n) {
if (!isValid(i, j, m, n) || grid[i][j] != '1' || visited[i][j]) return;
visited[i][j] = true;
dfs(grid, visited, i - 1, j, m, n);
dfs(grid, visited, i + 1, j, m, n);
dfs(grid, visited, i, j - 1, m, n);
dfs(grid, visited, i, j + 1, m, n);
}
private boolean isValid(int i, int j, int m, int n) {
return i >= 0 && i < m && j >= 0 && j < n;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment