首页 > 代码库 > Number of Islands
Number of Islands
This is Matrix Problem which can be converted to BSF:
Loop through each node, if it is island, find the edge. Inside the mark them all as sea. So it won‘t be recounted.
The most important thing for matrix BSF is to find the direction matrix, check whether it is in bound, and don‘t forget to remember which node has been searched.
One Tricky point: Pay attension to the inBound function. The code list the fast way to do it. If you pass the matrix, the time is limit wil reach.
public class Solution { /** * @param grid a boolean 2D matrix * @return an integer */ class Coordinate { int x; int y; public Coordinate (int x, int y) { this.x = x; this.y = y; } } 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 count = 0; for (int i = 0; i < grid.length; i++) { for (int j = 0; j < grid[0].length; j++) { if (grid[i][j]) { markEdge(grid, i, j); count++; } } } return count; } private void markEdge(boolean[][] grid, int x, int y) { int[] directX = {0, -1, 1, 0}; int[] directY = {-1, 0, 0, 1}; int nRow = grid.length; int nCol = grid[0].length; Coordinate original = new Coordinate(x, y); Queue<Coordinate> q = new LinkedList<Coordinate>(); q.offer(original); while (!q.isEmpty()) { Coordinate node = q.poll(); grid[node.x][node.y] = false; // This means this point has been checked. Since they belong to one queue, mark them as false means we don‘t have to make the count++ except the first time (in the main function, if is not satisified) for (int i = 0; i < directX.length; i++) { Coordinate neighbor = new Coordinate(node.x + directX[i], node.y + directY[i]); //System.out.println(neighbor.x + " " + neighbor.y); if (isInBound(neighbor, nRow, nCol) && grid[neighbor.x][neighbor.y]) { q.offer(neighbor); } } } } private boolean isInBound(Coordinate node, int row, int col) { int x = node.x; int y = node.y; return x >= 0 && x < row && y >= 0 && y < col; } //Slow way which cause the time limitation /*private boolean isInBound(boolean[][] grid, Coordinate node) { int nRow = grid.length; int nCol = grid[0].length; if (node.x < 0 || node.x >= nRow || node.y < 0 || node.y >= nCol) { return false; } return true; }*/ }
Number of Islands
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。