C++ Solution to Optimize sugeladi' s (9ms , beat 100%, DFS)


  • 0
    H
    class Solution {
    public:
        void solve(vector<vector<char>>& board) {
            
            if(board.size()<=0 || board[0].size()<=0)
                return;
            int row = board.size();
            int col = board[0].size();
            
            for(int i=0; i<row; i++)
            {
                if(board[i][0] == 'O')
                {
                    DFS(board, i, 0);
                }
                if(col>1 && board[i][col-1]=='O')
                {
                    DFS(board, i, col-1);
                }
            }
            for(int j=1; j<col-1; j++)
            {
                if(board[0][j] == 'O')
                {
                    DFS(board, 0, j);
                }
                if(row>1 && board[row-1][j]=='O')
                {
                    DFS(board,row-1,j);
                }
            }
            
            for(int i=0; i<row; i++)
            {
                for(int j=0; j<col; j++)
                {
                    board[i][j] = (board[i][j]=='1') ? 'O':'X';
                }
            }
            
            
                
            
        }
        
        void DFS(vector<vector<char>> &board, int i, int j)
        {
            board[i][j] = '1';
            int row = board.size();
            int col = board[0].size();
            if(i>1 && board[i-1][j]=='O')                    //up
            {
                DFS(board, i-1, j);
            }
            if(i<row-2 && board[i+1][j]=='O')                 //down
            {
                DFS(board, i+1, j);
            }
            if(j>1 && board[i][j-1]=='O')                    //left
            {
                DFS(board, i, j-1);
            }
            if(j<col-2 && board[i][j+1]=='O')                 //right
            {
                DFS(board, i, j+1);
            }
        }
    };
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.