1.深搜
func numIslands(_ grid: [[Character]]) -> Int {
var visit = Array.init(repeating: Array.init(repeating: false, count: grid[0].count), count: grid.count)
var count = 0
for i in 0..=0 && newX=0 && newY
2.宽搜
func numIslands(_ grid: [[Character]]) -> Int {
var visit = Array.init(repeating: Array.init(repeating: false, count: grid[0].count), count: grid.count)
var count = 0
var queue = [[Int]]()
for i in 0..=0 && newX=0 && newY
3. 并查集
class UnionFind: NSObject {
var parent:[Int]!
var count = 0
var rank:[Int]!
public init(_ grid:[[Character]]) {
let m = grid.count
let n = grid[0].count
parent = Array.init(repeating: 0, count: m*n)
rank = Array.init(repeating: 0, count: m*n)
for i in 0.. Int {
var x1 = x
while x1 != parent[x1] {
x1 = parent[x1]
}
return x1
}
func union(_ x:Int,_ y:Int) {
let rootx = find(x)
let rooty = find(y)
if rootx != rooty {
if rank[rootx] > rank[rooty] {
parent[rooty] = rootx
}else if rank[rootx] < rank[rooty]{
parent[rootx] = rooty
}else{
parent[rooty] = rootx
rank[rootx] += 1
}
count -= 1
}
}
}
func numIslands(_ oldGrid: [[Character]]) -> Int {
if oldGrid.count == 0 || oldGrid[0].count == 0 {
return 0
}
var grid = oldGrid
let nr = grid.count
let nc = grid[0].count
let uf = UnionFind.init(grid)
let directions = [[-1,0],[1,0],[0,1],[0,-1]]
for i in 0..=0 && newx=0 && newy
4.路径优化并查集
func find(_ x:Int,_ parent:[Int]) -> Int {
var x1 = x
while parent[x1] != x1 {
x1 = parent[x1]
}
return x1
}
func union(_ i:Int,_ j:Int,_ parent:inout [Int],_ count:inout Int) {
let x1 = find(i, parent)
let y1 = find(j, parent)
if x1 != y1 {//合并
parent[x1] = y1
count -= 1
}
}
/*
1. 访问过的状态置为0
2. 在区间范围内,且是1可以连通
*/
func numIslands(_ grid: [[Character]]) -> Int {
let row = grid.count
let col = grid[0].count
var count = 0//记录1的个数
var parent:[Int] = Array.init(repeating: 0, count: row*col)
for i in 0..=0 && newX=0 && newY