r#4 @
Allianzcortex #7
@
ryd994 #4
```
public class Solution {
int total;
int mapX, mapY;
class Node {
public int x, y;
public Node(int x, int y) {
this.x = x;
this.y = y;
}
@
Override public int hashCode() {
return (x + y) / 20;
}
@
Override public boolean equals(Object obj) {
Node objNode = (Node) obj;
if (objNode.x == this.x && objNode.y == this.y) {
return true;
}
return false;
}
}
Set<Node> nodeSet = new HashSet<Node>();
public int numIslands(boolean[][] grid) {
if (grid.length == 0){
return 0;
}
mapY = grid.length;
mapX = grid[0].length;
// Write your code here
for (int y = 0; y < grid.length; y++) {
for (int x = 0; x < grid[0].length; x++) {
if (grid[y][x] == false) {
continue;
}
Node temp = new Node(x, y);
if (grid[y][x] == true && !nodeSet.contains(temp)) {
nodeSet.add(temp);
buildIsland(temp, grid);
//todo
total++;
}
}
}
return total;
}
private void buildIsland(Node node, boolean[][] grid) {
Node curNode;
Stack<Node> stack = new Stack<Node>();
stack.push(node);
while (!stack.isEmpty()) {
Node temp = stack.pop();
int x = temp.x;
int y = temp.y;
if (isLegalNode(x - 1, y) && grid[y][x-1]) {
curNode = new Node(x - 1, y);
if (nodeSet.add(curNode)) {//第一次出现
stack.push(curNode);
}
}
if (isLegalNode(x + 1, y) && grid[y][x+1]) {
curNode = new Node(x + 1, y);
if (nodeSet.add(curNode)) {
stack.push(curNode);
}
}
if (isLegalNode(x, y - 1) && grid[y-1][x]) {
curNode = new Node(x, y - 1);
if (nodeSet.add(curNode)) {
stack.push(curNode);
}
}
if (isLegalNode(x, y + 1) && grid[y+1][x]) {
curNode = new Node(x, y + 1);
if (nodeSet.add(curNode)) {
stack.push(curNode);
}
}
}
}
private boolean isLegalNode(int x, int y) {
if (x >= 0 && x < mapX && y >= 0 && y < mapY) {
return true;
}
return false;
}
}
```