1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105
| type point struct { x int y int }
var dirct = [][]int{{1, 0}, {0, 1}, {0, -1}, {-1, 0}}
func numIslands(grid [][]byte) int { if len(grid) == 0 { return 0 } res := 0 r := len(grid) c := len(grid[0]) for i := 0; i < r; i++ { for j := 0; j < c; j++ { if grid[i][j] == '1' { res++ bfs(grid, i, j) } } } return res }
func bfs(grid [][]byte, i, j int) { r := len(grid) c := len(grid[0]) queue := []point{{i, j}} grid[i][j] = '0'
for len(queue) > 0 { current := queue[0] queue = queue[1:]
for _, item := range dirct { myRow := current.x + item[0] myCol := current.y + item[1]
if myRow >= 0 && myRow < r && myCol >= 0 && myCol < c && grid[myRow][myCol] == '1' { grid[myRow][myCol] = '0' queue = append(queue, point{myRow, myCol}) } } } }
type point struct { x int y int }
var dirct = [][]int{{1, 0}, {0, 1}, {0, -1}, {-1, 0}}
func numIslands(grid [][]byte) int { if len(grid) == 0 { return 0 } res := 0 r := len(grid) c := len(grid[0]) visited := make(map[point]int) for i := 0; i < r; i++ { for j := 0; j < c; j++ { if grid[i][j] == '1' { res++ dfs(grid, i, j, visited) } } } return res }
func dfs(grid [][]byte, i, j int, visited map[point]int) { r := len(grid) c := len(grid[0]) if i < 0 || j < 0 || i >= r || j >= c { return } if grid[i][j] == '0' { return } if _, ok := visited[point{i, j}]; ok { return } grid[i][j] = '0' visited[point{i, j}] = 1 for _, item := range dirct { myRow := i + item[0] myCol := j + item[1] if _, ok := visited[point{myRow, myCol}]; !ok { dfs(grid, myRow, myCol, visited) } } }
|