LC-岛屿数量
岛屿数量
Date Created: Sep 22, 2019 11:28 PM
Last Edited Time: Sep 27, 2019 5:39 PM
显示完成时间: Sep 23, 2019
状态: 已完成
真实完成时间: Sep 23, 2019
类型: leetcode
解法一
深度优先遍历,并且将遍历过的数据进行标记
func numIslands(grid [][]byte) int {
if len(grid) == 0 || len(grid[0]) == 0{
return 0
}
count := 0
for i, iNum := range grid {
for j, _ := range iNum {
if grid[i][j] == '1' {
count ++
dfs(grid, i, j)
}
}
}
return count
}
func dfs(grid [][]byte, i int, j int) {
grid[i][j] = '0'
if i - 1 >= 0 && grid[i-1][j] == '1' {
dfs(grid, i-1, j)
}
if j - 1 >= 0 && grid[i][j - 1] == '1' {
dfs(grid, i, j-1)
}
if i + 1 < len(grid) && grid[i+1][j] == '1' {
dfs(grid, i+1, j)
}
if j+1 < len(grid[0]) && grid[i][j+1] == '1' {
dfs(grid, i, j+1)
}
}
解法二
广度优先遍历,将遍历过的数据进行标记
func numIslands(grid [][]byte) int {
if len(grid) == 0 || len(grid[0]) == 0 {
return 0
}
isTouched := make([][]bool, len(grid))
for i, _ := range isTouched {
isTouched[i] = make([]bool, len(grid[0]))
}
count := 0
queue := list.New()
for i := 0; i < len(grid); i++ {
for j := 0; j < len(grid[0]); j++ {
if grid[i][j] == '1' {
count++
queue.PushBack(pos{i, j})
for queue.Len() > 0 {
ele := queue.Front()
v := queue.Remove(ele).(pos)
grid[v.i][v.j] = '0'
if v.i-1 >= 0 && !isTouched[v.i-1][v.j] && grid[v.i-1][v.j] == '1' {
queue.PushBack(pos{v.i - 1, v.j})
isTouched[v.i-1][v.j] = true
}
if v.j+1 < len(grid[0]) && !isTouched[v.i][v.j+1] && grid[v.i][v.j+1] == '1' {
queue.PushBack(pos{v.i, v.j + 1})
isTouched[v.i][v.j+1] = true
}
if v.i+1 < len(grid) && !isTouched[v.i+1][v.j] && grid[v.i+1][v.j] == '1' {
queue.PushBack(pos{v.i + 1, v.j})
isTouched[v.i+1][v.j] = true
}
if v.j-1 >= 0 && !isTouched[v.i][v.j-1] && grid[v.i][v.j-1] == '1' {
queue.PushBack(pos{v.i, v.j - 1})
isTouched[v.i][v.j-1] = true
}
}
}
}
}
return count
}
type pos struct {
i int
j int
}
本文来自博客园,作者:吴丹阳-V,转载请注明原文链接:https://www.cnblogs.com/wudanyang/p/11599461.html