本文主要是介绍Golang | Leetcode Golang题解之第130题被围绕的区域,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
题目:
题解:
var (dx = [4]int{1, -1, 0, 0}dy = [4]int{0, 0, 1, -1}
)
func solve(board [][]byte) {if len(board) == 0 || len(board[0]) == 0 {return}n, m := len(board), len(board[0])queue := [][]int{}for i := 0; i < n; i++ {if board[i][0] == 'O' {queue = append(queue, []int{i, 0})board[i][0] = 'A'}if board[i][m-1] == 'O' {queue = append(queue, []int{i, m - 1})board[i][m - 1] = 'A'}}for i := 1; i < m - 1; i++ {if board[0][i] == 'O' {queue = append(queue, []int{0, i})board[0][i] = 'A'}if board[n-1][i] == 'O' {queue = append(queue, []int{n - 1, i})board[n - 1][i] = 'A'}}for len(queue) > 0 {cell := queue[0]queue = queue[1:]x, y := cell[0], cell[1]for i := 0; i < 4; i++ {mx, my := x + dx[i], y + dy[i]if mx < 0 || my < 0 || mx >= n || my >= m || board[mx][my] != 'O' {continue}queue = append(queue, []int{mx, my})board[mx][my] = 'A'}}for i := 0; i < n; i++ {for j := 0; j < m; j++ {if board[i][j] == 'A' {board[i][j] = 'O'} else if board[i][j] == 'O' {board[i][j] = 'X'}}}
}
这篇关于Golang | Leetcode Golang题解之第130题被围绕的区域的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!