Golang | Leetcode Golang题解之第130题被围绕的区域

作者 : admin 本文共700个字,预计阅读时间需要2分钟 发布时间: 2024-06-9 共2人阅读

题目:

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  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 = 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'
            }
        }
    }
}
本站无任何商业行为
个人在线分享-虚灵IT资料分享 » Golang | Leetcode Golang题解之第130题被围绕的区域
E-->