본문 바로가기

Algorithm/LeetCode

[LeetCode][Python3] 130. Surrounded Regions

반응형
class Solution:
    def solve(self, board: List[List[str]]) -> None:
        """
        Do not return anything, modify board in-place instead.
        """
        if not board: return
        m = len(board)
        n = len(board[0])
        def isEdge(row,col):
            if 0<=row<m and 0<=col<n and board[row][col]=='O':
                board[row][col] ='#'
                isEdge(row-1,col)
                isEdge(row,col-1)
                isEdge(row+1,col)
                isEdge(row,col+1)
            else:
                return
            
            
        for row in range(0,m):
            isEdge(row,0)
            isEdge(row,n-1)
        for col in range(1,n-1):
            isEdge(0,col)
            isEdge(m-1,col)
        
        for i in range(m):
            for j in range(n):
                if board[i][j] =='#': board[i][j] = 'O'
                elif board[i][j]=='O': board[i][j]='X'
        

모서리에 있는 O들은 #으로 변경한 후, #을 O로, O를 X로 변경하면 된다.

반응형