Skip to content

Instantly share code, notes, and snippets.

@atiq-cs
Created January 30, 2019 01:57
Show Gist options
  • Save atiq-cs/1dc6ca38e523656d64e2e7bd2a192195 to your computer and use it in GitHub Desktop.
Save atiq-cs/1dc6ca38e523656d64e2e7bd2a192195 to your computer and use it in GitHub Desktop.
find num of island using graph search
// O(row*col), O(1), O(row+col) stack space
public class Solution {
char[][] grid;
public int NumIslands(char[,] grid) {
int count = 0;
for (int r=0; r<numRows; r++)
for (int c=0; c<numCols; c++)
if (grid[r][c] == '1') {
dfs(r, c);
count++;
}
return count;
}
void dfs(int r, int c) {
if (r < 0 || c < 0 || r >= numRows || c >= numCols || grid[r][c] != '1')
return ;
grid[r][c] = '0';
dfs(r-1, c);
dfs(r, c-1);
dfs(r, c+1);
dfs(r+1, c);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment