477. 被圍繞的區域
阿新 • • 發佈:2020-07-04
477.被圍繞的區域
中文English給一個二維的矩陣,包含'X'
和'O'
, 找到所有被'X'
圍繞的區域,並用'X'
替換其中所有的'O'
。
樣例
樣例 1:
輸入:
X X X X
X O O X
X X O X
X O X X
輸出:
X X X X
X X X X
X X X X
X O X X
樣例 2:
輸入:
X X X X
X O O X
X O O X
X O X X
輸出:
X X X X
X O O X
X O O X
X O X X
輸入測試資料(每行一個引數)如何理解測試資料?DFS + 邊界尋找 O 替換 T
O替換X,T替換O
class Solution: """ @param: board: board a 2D board containing 'X' and 'O' @return: nothing """ def surroundedRegions(self, board): # write your code here if not board: return #初始化 n, m = len(board), len(board[0]) def dfs(x, y):if (x < 0 or x > n - 1 or y < 0 or y > m - 1): return if board[x][y] == 'O': board[x][y] = 'T' dfs(x - 1, y) dfs(x + 1, y) dfs(x, y - 1) dfs(x, y + 1) #找尋邊界,如果滿足邊界 and 為0,則dfs找到上下左右的,換T #此時j為0和m- 1 for i in range(n): if (board[i][0] == 'O'): dfs(i, 0) if (board[i][m - 1] == 'O'): dfs(i, m - 1) for j in range(m): if (board[0][j] == 'O'): dfs(0, j) if (board[n - 1][j] == 'O'): dfs(n - 1, j) #然後迴圈m和n,依次將O轉換為X,並且T轉換為O for i in range(n): for j in range(m): if (board[i][j] == 'O'): #board[i] = board[i].replace(board[i][j], 'X', 1) board[i][j] = 'X' elif (board[i][j] == 'T'): board[i][j] = 'O' #board[i] = board[i].replace(board[i][j], 'O', 1) return board