简单的dfs
package main /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param grid int整型二维数组 * @return int整型 */ func maxAreaIsland( grid [][]int ) int { rowCount := len(grid) colCount := len(grid[0]) isVisited := make([][]bool, 0) maxSize := 0 for r := 0; r < rowCount; r++ { tmp := make([]bool, colCount) isVisited = append(isVisited, append([]bool(nil), tmp...)) } var dfs func(rowPos int, colPos int) int dfs = func(rowPos int, colPos int) int { if rowPos < 0 || rowPos >= rowCount || colPos < 0 || colPos >= colCount { return 0 } if isVisited[rowPos][colPos] || grid[rowPos][colPos] == 0 { return 0 } isVisited[rowPos][colPos] = true tmp := 1 tmp += dfs(rowPos-1, colPos) tmp += dfs(rowPos+1, colPos) tmp += dfs(rowPos, colPos-1) tmp += dfs(rowPos, colPos+1) if tmp > maxSize { maxSize = tmp } return tmp } for r := 0; r < rowCount; r++ { for c := 0; c < colCount; c++ { dfs(r, c) } } return maxSize }