99. 岛屿数量
本题思路,是用遇到一个没有遍历过的节点陆地,计数器就加一,然后把该节点陆地所能遍历到的陆地都标记上。
在遇到标记过的陆地节点和海洋节点的时候直接跳过。 这样计数器就是最终岛屿的数量。
package main
import (
"fmt"
)
// // DFS
// func numsIslands(grid [][]int) int {
// n := len(grid)
// if n == 0 {
// return 0
// }
// m := len(grid[0])
// count := 0
// var dfs func(x, y int)
// dfs = func(x, y int) {
// if x < 0 || x >= n || y < 0 || y >= m || grid[x][y] != 1 {
// return
// }
// grid[x][y] = 2
// dfs(x + 1, y)
// dfs(x - 1, y)
// dfs(x, y + 1)
// dfs(x, y - 1)
// }
// for i := 0; i < n; i++ {
// for j := 0; j < m; j++ {
// if grid[i][j] == 1 {
// count++
// dfs(i, j)
// }
// }
// }
// return count
// }
// BFS
func numsIslands(grid [][]int) int {
n := len(grid)
if n == 0 {
return 0
}
m := len(grid[0])
count := 0
directions := [][]int{{-1, 0}, {1, 0}, {0, -1}, {0, 1}}
var bfs func(x, y int)
bfs = func(x, y int) {
queue := [][]int{{x, y}}
grid[x][y] = 2
for len(queue) > 0 {
next := queue[0]
queue = queue[1: ]
i, j := next[0], next[1]
for _, d := range directions {
nexti, nextj := i + d[0], j + d[1]
if nexti >= 0 && nexti < n && nextj >= 0 && nextj < m && grid[nexti][nextj] == 1 {
queue = append(queue, []int{nexti, nextj})
grid[nexti][nextj] = 2
}
}
}
}
for i := 0; i < n; i++ {
for j := 0; j < m; j++ {
if grid[i][j] == 1 {
count++
bfs(i, j)
}
}
}
return count
}
func main() {
var n, m int
fmt.Scan(&n, &m)
grid := make([][]int, n)
for i := 0; i < n; i++ {
grid[i] = make([]int, m)
for j := 0; j < m; j++ {
fmt.Scan(&grid[i][j])
}
}
fmt.Println(numsIslands(grid))
}
100. 岛屿的最大面积
这道题目也是 dfs bfs基础类题目,就是搜索每个岛屿上“1”的数量,然后取一个最大的。
package main
import (
"fmt"
)
// // DFS
// func numsIslands(grid [][]int) int {
// n := len(grid)
// if n == 0 {
// return 0
// }
// m := len(grid[0])
// count := 0
// var dfs func(x, y int)
// dfs = func(x, y int) {
// if x < 0 || x >= n || y < 0 || y >= m || grid[x][y] != 1 {
// return
// }
// grid[x][y] = 2
// dfs(x + 1, y)
// dfs(x - 1, y)
// dfs(x, y + 1)
// dfs(x, y - 1)
// }
// for i := 0; i < n; i++ {
// for j := 0; j < m; j++ {
// if grid[i][j] == 1 {
// count++
// dfs(i, j)
// }
// }
// }
// return count
// }
// BFS
func numsIslands(grid [][]int) int {
n := len(grid)
if n == 0 {
return 0
}
m := len(grid[0])
count := 0
directions := [][]int{{-1, 0}, {1, 0}, {0, -1}, {0, 1}}
var bfs func(x, y int)
bfs = func(x, y int) {
queue := [][]int{{x, y}}
grid[x][y] = 2
for len(queue) > 0 {
next := queue[0]
queue = queue[1: ]
i, j := next[0], next[1]
for _, d := range directions {
nexti, nextj := i + d[0], j + d[1]
if nexti >= 0 && nexti < n && nextj >= 0 && nextj < m && grid[nexti][nextj] == 1 {
queue = append(queue, []int{nexti, nextj})
grid[nexti][nextj] = 2
}
}
}
}
for i := 0; i < n; i++ {
for j := 0; j < m; j++ {
if grid[i][j] == 1 {
count++
bfs(i, j)
}
}
}
return count
}
func main() {
var n, m int
fmt.Scan(&n, &m)
grid := make([][]int, n)
for i := 0; i < n; i++ {
grid[i] = make([]int, m)
for j := 0; j < m; j++ {
fmt.Scan(&grid[i][j])
}
}
fmt.Println(numsIslands(grid))
}