Created
January 30, 2019 01:57
-
-
Save atiq-cs/1dc6ca38e523656d64e2e7bd2a192195 to your computer and use it in GitHub Desktop.
find num of island using graph search
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
// 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