-
-
Save InterviewBytes/ae85e1afce451fb4437de3a9af6107e8 to your computer and use it in GitHub Desktop.
Number of Islands problem.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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