Given a boolean 2D matrix, 0 is represented as the sea, 1 is represented as the island. If two 1 is adjacent, we consider them in the same island. We only consider up/down/left/right adjacent.
Find the number of islands.
这个题目最不好想的一步是将所有相连的1都转换为0,使用到了bfs,因此要进行边界的判断。
java
class corr {
int x;
int y;
public corr(int x, int y) {
this.x = x;
this.y = y;
}
}
public class Solution {
/*
* @param grid: a boolean 2D matrix
* @return: an integer
*/
public int numIslands(boolean[][] grid) {
// write your code here
if (grid == null || grid.length == 0 || grid[0] == null || grid[0].length == 0) {
return 0;
}
int m = grid.length;
int n = grid[0].length;
int island = 0;
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (grid[i][j]) {
bfs(grid, i, j);
island++;
}
}
}
return island;
}
private void bfs(boolean[][] grid, int x, int y) {
int[] dirX = new int[]{0, 1, -1, 0};
int[] dirY = new int[]{1, 0, 0, -1};
grid[x][y] = false;
Queue<corr> queue = new LinkedList<>();
queue.offer(new corr(x, y));
while (!queue.isEmpty()) {
corr node = queue.poll();
for (int i = 0; i < 4; i++) {
int nx = node.x + dirX[i];
int ny = node.y + dirY[i];
if (!inBound(grid, nx, ny)) {
continue;
}
if (grid[nx][ny]) {
grid[nx][ny] = false;
queue.offer(new corr(nx, ny));
}
}
}
}
private boolean inBound(boolean[][] grid, int x, int y) {
int m = grid.length;
int n = grid[0].length;
return (x >= 0 && x < m && y >= 0 && y < n);
}
}
python
import Queue
class Solution:
"""
@param: grid: a boolean 2D matrix
@return: an integer
"""
def numIslands(self, grid):
# write your code here
if grid is None or len(grid) == 0 or grid[0] is None or len(grid[0]) == 0:
return 0
m, n, island = len(grid), len(grid[0]), 0
for i in range(m):
for j in range(n):
if grid[i][j]:
self.bfs(grid, i, j)
island += 1
return island
def bfs(self, grid, x, y):
dirX, dirY = [0, 1, -1, 0], [1, 0, 0, -1]
queue = Queue.Queue()
grid[x][y] = False
queue.put([x, y])
while not queue.empty():
node = queue.get()
for i in range(4):
n_x = node[0] + dirX[i]
n_y = node[1] + dirY[i]
if not self.inBound(grid, n_x, n_y):
continue
if grid[n_x][n_y]:
grid[n_x][n_y] = False
queue.put([n_x, n_y])
def inBound(self, grid, x, y):
m, n = len(grid), len(grid[0])
return x >= 0 and x < m and y >= 0 and y < n