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的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-12-27Nacos多环境配置学习入门
- 2024-12-27Nacos快速入门学习入门
- 2024-12-27Nacos快速入门学习入门
- 2024-12-27Nacos配置中心学习入门指南
- 2024-12-27Nacos配置中心学习入门
- 2024-12-27Nacos做项目隔离学习入门
- 2024-12-27Nacos做项目隔离学习入门
- 2024-12-27Nacos初识学习入门:轻松掌握服务发现与配置管理
- 2024-12-27Nacos初识学习入门:轻松掌握Nacos基础操作
- 2024-12-27Nacos多环境配置学习入门