LeetCode - Algorithms - 130. Surrounded Regions

Problem

130. Surrounded Regions

Java

BFS

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
class Solution {
private final static int d[][] = {
{0, 1},
{1, 0},
{0, -1},
{-1, 0}
};

public void solve(char[][] board) {
int h = board.length;
int w = h==0 ? 0 : board[0].length;

if (h==0 || w==0) return;

for (int j = 0; j < w; j++) {
if (board[0][j] == 'O') bfs(0, j, board, h, w);
if (board[h - 1][j] == 'O') bfs(h - 1, j, board, h, w);
}

for (int i = 1; i < h-1; i++) {
if (board[i][0] == 'O') bfs(i, 0, board, h, w);
if (board[i][w - 1] == 'O') bfs(i, w - 1, board, h, w);
}

for (int i = 0; i < h; i++) {
for (int j = 0; j < w; j++) {
if (board[i][j] == 'O') board[i][j] = 'X';
if (board[i][j] == 'B') board[i][j] = 'O';
}
}
}

private void bfs(int i, int j, char[][] board, int h, int w) {
Queue<Point> queue = new LinkedList<>();
queue.add(new Point(i,j));
while (!queue.isEmpty()) {
Point curr = queue.poll();
int row = curr.x;
int col = curr.y;
if (isValid(board, h, w, row, col)) {
board[row][col] = 'B';
for (int[] c: d) {
int x = curr.x + c[0];
int y = curr.y + c[1];
queue.add(new Point(x, y));
}
}
}
}

private boolean isValid(char[][] grid, int width, int height, int row, int col) {
return (row >= 0) && (row < width) && (col >= 0) && (col < height) && grid[row][col] == 'O';
}
}

class Point {
int x;
int y;

public Point(int x, int y) {
this.x = x;
this.y = y;
}
}

Submission Detail

  • 59 / 59 test cases passed.
  • Runtime: 2 ms, faster than 55.96% of Java online submissions for Surrounded Regions.
  • Memory Usage: 41.7 MB, less than 64.29% of Java online submissions for Surrounded Regions.

ref