200.岛屿数量
给你一个由 ‘1’(陆地)和 ‘0’(水)组成的的二维网格,请你计算网格中岛屿的数量。
岛屿总是被水包围,并且每座岛屿只能由水平方向和/或竖直方向上相邻的陆地连接形成。
此外,你可以假设该网格的四条边均被水包围。
示例 1:
输入:grid = [
[“1”,“1”,“1”,“1”,“0”],
[“1”,“1”,“0”,“1”,“0”],
[“1”,“1”,“0”,“0”,“0”],
[“0”,“0”,“0”,“0”,“0”]
示例 2:
输入:grid = [
题目:http://poj.org/problem?id=2492
题的解答方法跟食物链差不多,可以看看食物链的解析再看这个。
食物链 http://blog.csdn.net/dreambyday/article/details/65447189
rela[x]=0表示同性
rela[x]=1表示异性#include
#include
#includ
import java.util.HashMap;
class UnionFind {
private HashMap<Integer, Integer> parent = new HashMap<>(); public UnionFind(int n) {
for (int i = 0; i < n; i++) {
parent.put(i, i);
} public int find(int x) {
int parentX = parent.get(x);
if (parentX == x) {
return x;
int ancestor = find(parentX);
//
路径压缩
parent.put(x, ancestor);
return ancestor;
} public void union(int x, int y) {
int ancestorX = find(x);
int ancestorY = find(y);
if (ancestorX == ancestorY) {
return;
parent.put(ancestorX, ancestorY);
}答案:我可以为您提供一段用Java写出
并查集的代码:
import java.util.HashMap;
class UnionFind {
private HashMap<Integer, Integer> parent = new HashMap<>(); public UnionFind(int n) {
for (int i = 0; i < n; i++) {
parent.put(i, i);
} public int find(int x) {
int parentX = parent.get(x);
if (parentX == x) {
return x;
int ancestor = find(parentX);
//
路径压缩
parent.put(x, ancestor);
return ancestor;
} public void union(int x, int y) {
int ancestorX = find(x);
int ancestorY = find(y);
if (ancestorX == ancestorY) {
return;
parent.put(ancestorX, ancestorY);