Algorithm title: Number of islands
Difficulty: Intermediate
Implementation language: Golang
Islands. png
Idea: Starting from the vertex (0,0), respectively to the left and right to traverse, meet 1 set to 0, meet 0 stop, traverse to 4 directions are 1 plus 1
package mainimport "fmt"func main() { var graph1 = [5][5]int{ {1, 1, 0, 0, 0}, {1, 1, 0, 0, 0}, {0, 0, 1, 0, 0}, {0, 0, 0, 1, 1}, } graph1 = [5][5]int{ {1, 1, 1, 1, 0}, {1, 1, 0, 1, 0}, {1, 1, 0, 0, 0}, {0, 0, 0, 0, 0}, } var count int for i := 0; i < 5; i++ { for j := 0; j < 5; j++ { if graph1[i][j] == 1 { search(&graph1, i, j) count++ } } } fmt.Println(count)}func search(graph1 *[5][5]int, i, j int) { if i < 0 || i >= 5 || j >= 5 || j < 0 || graph1[i][j] == 0 { return } graph1[i][j] = 0 search(graph1, i-1, j) search(graph1, i+1, j) search(graph1, i, j+1) search(graph1, i, j-1)}