Number of Islands
Posted codingEskimo
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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的主要内容,如果未能解决你的问题,请参考以下文章