|
| 1 | +# coding: utf8 |
| 2 | + |
| 3 | + |
| 4 | +""" |
| 5 | + 题目链接: https://leetcode.com/problems/surrounded-regions/description. |
| 6 | + 题目描述: |
| 7 | +
|
| 8 | + Given a 2D board containing 'X' and 'O' (the letter O), capture all regions surrounded by 'X'. |
| 9 | +
|
| 10 | + A region is captured by flipping all 'O's into 'X's in that surrounded region. |
| 11 | +
|
| 12 | + For example, |
| 13 | + X X X X |
| 14 | + X O O X |
| 15 | + X X O X |
| 16 | + X O X X |
| 17 | + After running your function, the board should be: |
| 18 | +
|
| 19 | + X X X X |
| 20 | + X X X X |
| 21 | + X X X X |
| 22 | + X O X X |
| 23 | +
|
| 24 | +""" |
| 25 | + |
| 26 | + |
| 27 | +class Solution(object): |
| 28 | + def solve(self, board): |
| 29 | + """ |
| 30 | + :type board: List[List[str]] |
| 31 | + :rtype: void Do not return anything, modify board in-place instead. |
| 32 | + """ |
| 33 | + if not any(board): |
| 34 | + return |
| 35 | + |
| 36 | + rows, columns = len(board), len(board[0]) |
| 37 | + for i in range(rows): |
| 38 | + for j in range(columns): |
| 39 | + if i == 0 or i == rows - 1 or j == 0 or j == columns - 1 and board[i][j] == 'O': |
| 40 | + self.dfs(board, rows, columns, i, j) |
| 41 | + |
| 42 | + for i in range(rows): |
| 43 | + for j in range(columns): |
| 44 | + if board[i][j] == 'O': |
| 45 | + board[i][j] = 'X' |
| 46 | + elif board[i][j] == '$': |
| 47 | + board[i][j] = 'O' |
| 48 | + |
| 49 | + def dfs(self, board, rows, columns, i, j): |
| 50 | + if i < 0 or i >= rows or j < 0 or j >= columns or board[i][j] != 'O': |
| 51 | + return |
| 52 | + |
| 53 | + board[i][j] = '$' |
| 54 | + self.dfs(board, rows, columns, i - 1, j) |
| 55 | + self.dfs(board, rows, columns, i, j + 1) |
| 56 | + self.dfs(board, rows, columns, i + 1, j) |
| 57 | + self.dfs(board, rows, columns, i, j - 1) |
0 commit comments