中文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
classsolution:
""" @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
bfs寫法 + 邊界查詢 替換法
classsolution:
""" @param: board: board a 2d board containing '
x' and 'o'
@return: nothing
"""def surroundedregions(self, board):
# write your code here
#bfs寫法,每次只fill一次,查詢一次,符合則替換,最終返回結果
if not board: return
m, n = len(board[0
]), len(board)
queue =
def fill(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'
def bfs(x ,y):
fill(x, y)
while
queue:
curr = queue.pop(0
) x, y = curr[0], curr[1
]
fill(x + 1
, y)
fill(x - 1
, y)
fill(x, y + 1
) fill(x, y - 1
)
#邊界查詢
#x軸查詢
for i in
range(n):
if (board[i][0] == 'o'
): bfs(i ,0)
if (board[i][m - 1] == 'o'
): bfs(i, m - 1
)
#y軸查詢
for j in
range(m):
if (board[0][j] == 'o'
): bfs(
0, j)
if (board[n - 1][j] == 'o'
): bfs(n - 1
, j)
#最終替換
for i in
range(m):
for j in
range(n):
if (board[j][i] == 'o'
): board[j][i] = 'x'
elif (board[j][i] == 't'
): board[j][i] = 'o'
return
board
LintCode 477 被圍繞的區域
題意 給乙個二維的矩陣,包含 x 和 o 找到所有被 x 圍繞的區域,並用 x 填充滿。樣例 給出的二維矩陣 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 x o x x 解題思路 1 用bfs確定連...
lintcode 477 被圍繞的區域
給乙個二維的矩陣,包含 x 和 o 找到所有被 x 圍繞的區域,並用 x 填充滿。樣例給出二維矩陣 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 x o x x 標籤union find 寬度優先搜尋...
兩次過 Lintcode 477 被圍繞的區域
給乙個二維的矩陣,包含 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...