leetcode @python 130. Surrounded Regions
2016-04-03 11:22
555 查看
题目链接
https://leetcode.com/problems/surrounded-regions/题目原文
Given a 2D board containing 'X' and 'O', capture all regions surrounded by 'X'.A region is captured by flipping all 'O's into 'X's in that surrounded region.
For example,
X X X X
X O O X
X X O X
X O X X
After running your function, the board should be:
X X X X
X X X X
X X X X
X O X X
题目大意
给出一个铺满O或者X的区域,将被X围住的O都换成X解题思路
使用BFS从边上开始搜索,如果是'O',那么搜索'O'周围的元素,并将'O'置换为'D',这样每条边都DFS或者BFS一遍。而内部的'O'是不会改变的。这样下来,没有被围住的'O'全都被置换成了'D',被围住的'O'还是'O',没有改变。然后遍历一遍,将'O'置换为'X',将'D'置换为'O'。
代码
class Solution(object): def solve(self, board): """ :type board: List[List[str]] :rtype: void Do not return anything, modify board in-place instead. """ def fill(x, y): if x < 0 or x > m - 1 or y < 0 or y > n - 1 or board[x][y] != 'O': return queue.append((x, y)) board[x][y] = 'D' def bfs(x, y): if board[x][y] == 'O': fill(x, y) while queue: cur = queue.pop(0) i = cur[0] j = cur[1] fill(i + 1, j) fill(i - 1, j) fill(i, j + 1) fill(i, j - 1) if len(board) == 0: return m = len(board) n = len(board[0]) queue = [] for i in range(n): bfs(0, i) bfs(m - 1, i) for j in range(1, m - 1): bfs(j, 0) bfs(j, n - 1) for i in range(m): for j in range(n): if board[i][j] == 'D': board[i][j] = 'O' elif board[i][j] == 'O': board[i][j] = 'X'
相关文章推荐
- 自动化测试常用断言的使用方法(python)
- leetcode @python 129. Sum Root to Leaf Numbers
- leetcode @python 128. Longest Consecutive Sequence
- leetcode @python 127. Word Ladder
- python中的operator库
- 如何配置OPENCV的Python接口
- Python基础之数据类型
- java和python对比
- python的注释
- Python之路【第十八篇】Django小项目简单BBS论坛部分内容知识点
- python中的字符串
- python中yaml模块的使用
- Python3使用requests模块显示下载进度
- Python及bs4、lxml、numpy模块包的安装
- python3 发送邮件功能
- python魔法 交换两个数字
- python 中斐波那契数列的那些事
- python快速排序
- Python 模块动态加载技术
- Python2.6.6执行selenium自动化