전형적인 bfs문제이다.
시간복잡도는 O(grid 요소의 갯수)와 같다.
import java.util.*;
class Solution {
public static int dr[] = { 0, 1, 0, -1 };
public static int dc[] = { 1, 0, -1, 0 };
public int numIslands(char[][] grid) {
int answer = 0;
for (int i = 0; i < grid.length; i++) {
for (int j = 0; j < grid[i].length; j++) {
if (grid[i][j] == '1') {
answer++;
grid[i][j] = '0';
bfs(i, j, grid);
}
}
}
return answer;
}
public static void bfs(int row, int col, char[][] grid) {
Queue<Position> queue = new LinkedList<Position>();
queue.add(new Position(row, col));
while (!queue.isEmpty()) {
Position now = queue.poll();
for (int i = 0; i < 4; i++) {
int newRow = now.row + dr[i];
int newCol = now.col + dc[i];
if (isBoundary(newRow, newCol, grid) && grid[newRow][newCol] == '1') {
grid[newRow][newCol] = '0';
queue.add(new Position(newRow, newCol));
}
}
}
}
public static boolean isBoundary(int row, int col, char[][] grid) {
if (row < 0) {
return false;
}
if (row >= grid.length) {
return false;
}
if (col < 0) {
return false;
}
if (col >= grid[row].length) {
return false;
}
return true;
}
}
class Position {
int row, col;
public Position(int row, int col) {
this.row = row;
this.col = col;
}
}
'알고리즘 공부 > leetcode' 카테고리의 다른 글
leetcode: Range Sum Query - Mutable (0) | 2021.01.10 |
---|---|
leetcode: 01 Matrix (0) | 2021.01.08 |
leetcode: Trapping Rain Water (0) | 2020.12.27 |
leetcode: Median of two sorted Arrays (0) | 2020.12.26 |
leetcode: Letter Combinations of a Phone number (0) | 2020.12.26 |