-
Notifications
You must be signed in to change notification settings - Fork 126
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
a8adc1b
commit 8294a51
Showing
1 changed file
with
41 additions
and
0 deletions.
There are no files selected for viewing
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,41 @@ | ||
class SolutionNumberOfIslands { | ||
char[][] sharedGrid; | ||
int[] dx = new int[]{0, 0, -1, 1}; | ||
int[] dy = new int[]{-1, 1, 0, 0}; | ||
|
||
public int numIslands(char[][] grid) { | ||
// νμ΄ | ||
// λ€ λͺ¨μλ¦¬κ° λ¬Όλ‘ λλ¬μμ¬μμΌλ©΄ μμΌλλ | ||
// μμΌλλμ κ°μλ₯Ό λ°νν΄λΌ | ||
// λ μΈ κ²½μ° DFS λλ €μ μννμ | ||
// μνμ’μ° νμΈνλ©΄μ λ μ΄λ©΄ λ¬Όλ‘ λ³κ²½νλ©΄μ μννλ€ | ||
// DFS 1ν λΉ answer += 1 | ||
// TC: O(N), Nμ λ°°μ΄ μμ κ°μ | ||
// SC: O(N) | ||
var answer = 0; | ||
|
||
sharedGrid = grid; | ||
for (int i=0; i<grid.length; i++) { | ||
for (int j=0; j<grid[0].length; j++) { | ||
if (sharedGrid[i][j] == '1') { | ||
dfs(i, j); | ||
answer++; | ||
} | ||
} | ||
} | ||
|
||
return answer; | ||
} | ||
|
||
private void dfs(int i, int j) { | ||
sharedGrid[i][j] = '0'; | ||
|
||
for (int k=0; k<4; k++) { | ||
var x = i+dx[k]; | ||
var y = j+dy[k]; | ||
if (x >= 0 && y >= 0 && x < sharedGrid.length && y < sharedGrid[0].length && sharedGrid[x][y] == '1') { | ||
dfs(x, y); | ||
} | ||
} | ||
} | ||
} |