Skip to content

Commit 9ef808d

Browse files
committed
number of islands
1 parent 57fa3e8 commit 9ef808d

1 file changed

Lines changed: 52 additions & 0 deletions

File tree

number-of-islands/se6816.java

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
/**
2+
방문하지 않는 지점을 찾고, BFS로 인근 지점을 방문처리하며, 방문하지 않는 지점 개수를 카운틷하는 방식
3+
*/
4+
class Solution {
5+
int M;
6+
int N;
7+
boolean[][] visited;
8+
int[] moveX = {-1, 0, 0, 1};
9+
int[] moveY = {0, -1, 1, 0};
10+
public int numIslands(char[][] grid) {
11+
int result = 0;
12+
M = grid.length;
13+
N = grid[0].length;
14+
visited= new boolean[M][N];
15+
for(int i = 0; i < M; i++) {
16+
for(int j = 0; j < N; j++) {
17+
if(!visited[i][j] && grid[i][j] == '1') {
18+
visited[i][j] = true;
19+
result++;
20+
paint(i, j, visited, grid);
21+
}
22+
}
23+
}
24+
return result;
25+
26+
}
27+
public void paint(int x, int y, boolean[][] visited, char[][] grid) {
28+
for(int i = 0; i < 4; i++) {
29+
int tempX = x + moveX[i];
30+
int tempY = y + moveY[i];
31+
32+
if(isOutOfIndex(tempX, tempY)) {
33+
continue;
34+
}
35+
36+
if(visited[tempX][tempY]) {
37+
continue;
38+
}
39+
40+
if(grid[tempX][tempY] == '0') {
41+
continue;
42+
}
43+
44+
visited[tempX][tempY] = true;
45+
46+
paint(tempX,tempY, visited, grid);
47+
}
48+
}
49+
public boolean isOutOfIndex(int x, int y) {
50+
return x < 0 || x >= M || y < 0 || y >=N;
51+
}
52+
}

0 commit comments

Comments
 (0)