130被围绕的区域
Posted cong12586
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了130被围绕的区域相关的知识,希望对你有一定的参考价值。
from typing import List
# 这道题看了大佬写的代码,经过自己的理解写出来了。
# 从最外围的四周找有没有为O的,如果有的话就进入深搜函数,然后深搜遍历
# 判断上下左右的位置是否为O
class Solution:
def solve(self, board: List[List[str]]) -> None:
# 判断是否为空列表
if not board or not board[0] : return
# 求出列表的有几行和有几列
row = len(board)
col = len(board[0])
# 深搜,当边界为O进行判断
def dfs(index1,index2):
# 首先将O变成B,之后再变回来。
board[index1][index2] = ‘B‘
# 遍历上下左右
for x,y in [(0,1),(0,-1),(1,0),(-1,0)]:
print(x,y)
# 注意这里不能改变index1和index2的值,因为后边还要用。
i = index1 + x
j = index2 + y
# 如果当前位置的上下左右不出边界而且位置上为O就,进行深搜
# 注意这里边界上边不能判断,
if 1 <= i < row and 1 <= j < col and board[i][j] == "O":
print("111")
dfs(i,j)
# 判断第一行和最后一行上的边界值
for index1 in range(col):
if board[0][index1] == "O":
dfs(0,index1)
if board[row - 1][index1] == ‘O‘:
dfs(row - 1,index1)
# 判断第一列和最后一列的边界值
for index2 in range(row):
if board[index2][0] == "O":
dfs(index2,0)
if board[index2][col - 1] == ‘O‘:
dfs(index2,col - 1)
# 将O全部改写成X,将之前写的B也改写成O
for index1 in range(row):
for index2 in range(col):
if board[index1][index2] == "O":
board[index1][index2] = "X"
if board[index1][index2] == "B":
board[index1][index2] = ‘O‘
A = Solution()
print(A.solve([["O","X","X","O","X"],["X","O","O","X","O"],["X","O","X","O","X"],["O","X","O","O","O"],["X","X","O","X","O"]])
)
以上是关于130被围绕的区域的主要内容,如果未能解决你的问题,请参考以下文章