leetcode 130

2021/8/7 23:36:29

本文主要是介绍leetcode 130,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

https://leetcode.com/problems/surrounded-regions/

题目要求把四周被X包围的O块去掉. 所以没有被去掉的O块一定是在边上. 我的想法是标记所有于周边相连的O块即可. 具体方法可以依次使用广度优先.

1, 对周围一圈的O依次使用广度优先(深度优先亦可) 标记为1.

2, 遍历矩阵将O改为X

3, 遍历矩阵将1改回O

`class Solution:

def update_info(self, board, i, j, row_num, col_num):
    if i < 0 or j < 0 or i >= row_num or j >= col_num:
        return
    if board[i][j] == "O":
        board[i][j] = "1"
        # print(i, j)
        for m in (i-1, i+1):
            self.update_info(board, m, j, row_num, col_num)

        for n in (j+1, j-1):
                self.update_info(board, i, n, row_num, col_num)
    return


def solve(self, board: List[List[str]]) -> None:
    """
    Do not return anything, modify board in-place instead.
    """
    if not board or not board[0]:
        return
      
    row_num = len(board)
    col_num = len(board[0])
    if row_num == 1 or col_num == 1:
        return
    
    for i in range(row_num):
        for j in (0, col_num-1):
            self.update_info(board, i, j, row_num, col_num)

    for i in (0, row_num - 1):
        for j in range(col_num):
            self.update_info(board, i, j, row_num, col_num)


    for i in range(row_num):
        for j in range(col_num):
            if board[i][j] == "O":
                board[i][j] = "X"
    
    for i in range(row_num):
        for j in range(col_num):
            if board[i][j] == "1":
                board[i][j] = "O"`


这篇关于leetcode 130的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程