Skip to content

Instantly share code, notes, and snippets.

@aniruddha84
Last active January 19, 2018 17:48
Show Gist options
  • Save aniruddha84/66f9fb20edc65660d24d8384fbcb6c3e to your computer and use it in GitHub Desktop.
Save aniruddha84/66f9fb20edc65660d24d8384fbcb6c3e to your computer and use it in GitHub Desktop.
Find max area island in Matrix
class Solution {
public int maxAreaOfIsland(int[][] matrix) {
int rows = matrix.length;
int cols = matrix[0].length;
// return if empty matrix
if (cols == 0) return 0;
int[][] visited = new int[rows][cols];
int maxArea = 0;
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
// if value is 1 and not visited
if (matrix[i][j] == 1 && visited[i][j] == 0) {
int area = dfs(matrix, i, j, visited);
maxArea = Math.max(area, maxArea);
}
}
}
return maxArea;
}
private int dfs(int[][] matrix, int row, int col, int[][] visited) {
if ((row < 0 || row >= matrix.length) || (col < 0 || col >= matrix[0].length)) return 0;
if (visited[row][col] == 1) return 0;
if (matrix[row][col] == 0) return 0;
visited[row][col] = 1;
return 1 +
dfs(matrix, row, col - 1, visited) +
dfs(matrix, row - 1, col, visited) +
dfs(matrix, row, col + 1, visited) +
dfs(matrix, row + 1, col, visited);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment