Skip to content
Permalink
master
Switch branches/tags

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?
Go to file
 
 
Cannot retrieve contributors at this time
Given a 2D board containing 'X' and 'O' (the letter O), capture all regions surrounded by 'X'.

A region is captured by flipping all 'O's into 'X's in that surrounded region.

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
Explanation:

Surrounded regions shouldn’t be on the border, which means that any 'O' on the border of the board are not flipped to 'X'. Any 'O' that is not on the border and it is not connected to an 'O' on the border will be flipped to 'X'. Two cells are connected if they are adjacent cells connected horizontally or vertically.

My code:

class Solution(object):
    def solve(self, board):
        """
        :type board: List[List[str]]
        :rtype: void Do not return anything, modify board in-place instead.
        """
        m=len(board)
        if m<=2:
            return
        example=board[0]
        n=len(example)
        if n<=2:
            return
        self.m=m
        self.n=n
        self.record=[[0]*n for i in range(m)]
        #Init self.record by the boarder
        i=0
        for k in range(n):
            if board[i][k]=='O':
                self.extend(board,i,k)
        i=m-1
        for k in range(n):
            if board[i][k]=='O':
                self.extend(board,i,k)
        j=0
        for k in range(m):
            if board[k][j]=='O':
                self.extend(board,k,j)
        j=n-1
        for k in range(m):
            if board[k][j]=='O':
                self.extend(board,k,j)
        for i in range(m):
            for j in range(n):
                if self.record[i][j]==0 and board[i][j]=='O':
                    board[i][j]='X'
    def extend(self,board,i,j):
        
        if i>=self.m:
            return
        if j>=self.n:
            return 
        if i<0 or j<0:
            return
        if self.record[i][j]==1:
            return
        if board[i][j]=='O':
            self.record[i][j]=1
            self.extend(board,i+1,j)
            self.extend(board,i,j+1)
            self.extend(board,i-1,j)
            self.extend(board,i,j-1)
        
        
        

Solution: https://leetcode.com/problems/surrounded-regions/