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 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84
| package com.jarome.leetcode;
import java.util.LinkedList; import java.util.Queue;
public class SolutionIsland {
public int numIslands(char[][] grid) { int islandSize = 0; int ySize = grid.length; for (int i = 0; i < ySize; i++) { char[] item = grid[i]; int xSize = item.length; for (int j = 0; j < xSize; j++) { char itemValue = item[j]; if (itemValue != '1') { continue; } islandSize++; grid[i][j] = '0'; Queue<Point> queue = new LinkedList<Point>(); Point start = new Point(j, i); queue.add(start); while (!queue.isEmpty()) { Point remove = queue.remove(); int x = remove.getX(); int y = remove.getY(); deal(queue, grid, x, y - 1, xSize, ySize); deal(queue, grid, x, y + 1, xSize, ySize); deal(queue, grid, x - 1, y, xSize, ySize); deal(queue, grid, x + 1, y, xSize, ySize);
} } } return islandSize; }
private void deal(Queue<Point> queue, char[][] grid, int x, int y, int xSize, int ySize) { if ((x >= 0 && x < xSize) && (y >= 0 && y < ySize) && grid[y][x] == '1') { grid[y][x] = '0'; Point next = new Point(x, y); queue.add(next); } }
static class Point { private int x; private int y;
public Point(int x, int y) { this.x = x; this.y = y; }
public int getX() { return x; }
public void setX(int x) { this.x = x; }
public int getY() { return y; }
public void setY(int y) { this.y = y; } }
}
|