Skip to content

Commit 916cfe1

Browse files
donghyeon95donghyeon95
authored andcommitted
feat: Number of Islands #258
1 parent df69057 commit 916cfe1

File tree

1 file changed

+34
-0
lines changed

1 file changed

+34
-0
lines changed

number-of-islands/donghyeon95.java

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
class Solution {
2+
3+
int[][] moves = {{1,0}, {-1,0}, {0,1}, {0,-1}};
4+
boolean[][] visited;
5+
public int numIslands(char[][] grid) {
6+
// 섬의 갯수 => 0혹은 경계선으로 둘러싸인 것의 갯수
7+
// dfs로 탐색
8+
int result = 0;
9+
visited = new boolean[grid.length][grid[0].length];
10+
11+
for (int i=0; i<grid.length; i++) {
12+
for (int j=0; j<grid[0].length; j++) {
13+
if (grid[i][j] == '1' && !visited[i][j]) {
14+
dfs(i, j, grid);
15+
result++;
16+
}
17+
}
18+
}
19+
20+
return result;
21+
}
22+
23+
public void dfs(int y, int x, char[][] grid) {
24+
visited[y][x] = true;
25+
26+
for (int[] move: moves) {
27+
int newX = x + move[0];
28+
int newY = y + move[1];
29+
30+
if (newX<0 || newX >= grid[0].length || newY<0 || newY >= grid.length || visited[newY][newX] || grid[newY][newX]=='0') continue;
31+
dfs(newY, newX, grid);
32+
}
33+
}
34+
}

0 commit comments

Comments
 (0)