Skip to content

Commit 8294a51

Browse files
number of Islands solution
1 parent a8adc1b commit 8294a51

File tree

1 file changed

+41
-0
lines changed

1 file changed

+41
-0
lines changed

β€Žnumber-of-islands/jaejeong1.java

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
class SolutionNumberOfIslands {
2+
char[][] sharedGrid;
3+
int[] dx = new int[]{0, 0, -1, 1};
4+
int[] dy = new int[]{-1, 1, 0, 0};
5+
6+
public int numIslands(char[][] grid) {
7+
// 풀이
8+
// λ„€ λͺ¨μ„œλ¦¬κ°€ 물둜 λ‘˜λŸ¬μŒ“μ—¬μžˆμœΌλ©΄ μ•„μΌλžœλ“œ
9+
// μ•„μΌλžœλ“œμ˜ 개수λ₯Ό λ°˜ν™˜ν•΄λΌ
10+
// 땅인 경우 DFS λŒλ €μ„œ μˆœνšŒν•˜μž
11+
// μƒν•˜μ’Œμš° ν™•μΈν•˜λ©΄μ„œ 땅이면 물둜 λ³€κ²½ν•˜λ©΄μ„œ μˆœνšŒν•œλ‹€
12+
// DFS 1회 λ‹Ή answer += 1
13+
// TC: O(N), N은 λ°°μ—΄ μ›μ†Œ 개수
14+
// SC: O(N)
15+
var answer = 0;
16+
17+
sharedGrid = grid;
18+
for (int i=0; i<grid.length; i++) {
19+
for (int j=0; j<grid[0].length; j++) {
20+
if (sharedGrid[i][j] == '1') {
21+
dfs(i, j);
22+
answer++;
23+
}
24+
}
25+
}
26+
27+
return answer;
28+
}
29+
30+
private void dfs(int i, int j) {
31+
sharedGrid[i][j] = '0';
32+
33+
for (int k=0; k<4; k++) {
34+
var x = i+dx[k];
35+
var y = j+dy[k];
36+
if (x >= 0 && y >= 0 && x < sharedGrid.length && y < sharedGrid[0].length && sharedGrid[x][y] == '1') {
37+
dfs(x, y);
38+
}
39+
}
40+
}
41+
}

0 commit comments

Comments
Β (0)