Skip to content

Instantly share code, notes, and snippets.

@shixiaoyu
Created May 25, 2020 18:30
Show Gist options
  • Save shixiaoyu/fe8cda2173428a6df63121f7c9b30464 to your computer and use it in GitHub Desktop.
Save shixiaoyu/fe8cda2173428a6df63121f7c9b30464 to your computer and use it in GitHub Desktop.
public class Block {
public int x;
public int y;
public Block(int x, int y) {
this.x = x;
this.y = y;
}
}
public int numIslandsBFS(char[][] grid) {
if (grid == null || grid.length == 0 || grid[0].length == 0) {
return 0;
}
int m = grid.length;
int n = grid[0].length;
boolean[][] visited = new boolean[m][n];
int count = 0;
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (grid[i][j] == '0' || visited[i][j]) {
continue;
}
count++;
visited[i][j] = true;
Queue<Block> q = new LinkedList<>(); // queue just uses LinkedList, ArrayList doesn't implement it
// remind myself what's the diff between offer and add,
// some implementation it's the same, some add throws while offer return true/false if the queue is
// full while you still trying to add
q.offer(new Block(i, j));
while (!q.isEmpty()) {
Block b = q.poll();
for (int k = 0; k < 4; k++) {
int x = b.x + xDirection[k];
int y = b.y + yDirection[k];
if (this.shouldExplore(x, y, m, n, grid, visited)) {
visited[x][y] = true;
q.offer(new Block(x, y));
}
}
}
}
}
return count;
}
private boolean shouldExplore(int x, int y, int row, int col, char[][] grid, boolean[][] visited) {
if (x >= 0 && x < row && y >= 0 && y < col && grid[x][y] == '1' && !visited[x][y]) return true;
return false;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment