A simple solution using JavaScript


  • 0
    J
    /**
     * @param {character[][]} board
     * @return {void} Do not return anything, modify board in-place instead.
     */
    
    var stack=[];
    var s=[];
    
    function BFS(i,j,n,m){
        var flag=1;
        stack.push([i,j]);
        s[i][j]=1;
        if(i===0||j===0||i===n-1||j===m-1){
            flag=0;
        }
        if(i>0&&s[i-1][j]===0){
            flag=flag*BFS(i-1,j,n,m);
        }
        if(j>0&&s[i][j-1]===0){
            flag=flag*BFS(i,j-1,n,m);
        }
        if(i<n-1&&s[i+1][j]===0){
            flag=flag*BFS(i+1,j,n,m);
        }
        if(j<m-1&&s[i][j+1]===0){
            flag=flag*BFS(i,j+1,n,m);
        }
        
        return flag;
    }
    
    var solve = function(board) {
        var n;
        var m;
        if(board.length===0)
        {n=0;m=0;}
        else{
            n=board.length;
            if(typeof(board[0].length)==='undefined')
                m=0;
            else
                m=board[0].length;
        }
        var i,j;
        for(i=0;i<n;i++){
            s[i]=[];
            for(j=0;j<m;j++)
                s[i][j]=1;
        }
        for(i=0;i<n;i++)
            for(j=0;j<m;j++){
                if(board[i][j]==='O'){
                    s[i][j]=0;
                }
            }
        for(i=0;i<n;i++)
            for(j=0;j<m;j++){
                if(s[i][j]===0){
                    var re=BFS(i,j,n,m);
                    if(re===1)
                        while(stack.length>0){
                            var u=stack[stack.length-1][0];
                            var v=stack[stack.length-1][1];
                            board[u][v]='X';
                            stack.pop();
                        }
                    else
                        while(stack.length>0){
                            stack.pop();
                        }
                }
            }
       
    };
    

    Don't ask me why I used JS.


Log in to reply
 

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