Skip to content

Commit

Permalink
number of Islands solution
Browse files Browse the repository at this point in the history
  • Loading branch information
wad-jangjaejeong committed Sep 22, 2024
1 parent a8adc1b commit 8294a51
Showing 1 changed file with 41 additions and 0 deletions.
41 changes: 41 additions & 0 deletions number-of-islands/jaejeong1.java
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);
}
}
}
}

0 comments on commit 8294a51

Please sign in to comment.