130. Surrounded Regions

被自己蠢哭了。
visit[i][j] = true写成了visit[j][j] = true 我DEBUG了1个多小时。。。。。。。

image

从最外面那圈的所有O开始顺着相邻的O走,里面那些能走到的O就是不用变成反革命分子的。否则最后变成X,反革命分子。

主要是剪枝,乱七八糟一大堆情况,包括但不限于:

走到边了,走出界了,已经接受过组织的审查了, 他本身就是反革命分子,etc..

一开始4*4 test case没问题让我以为代码是正确的。结果后来各种stackoverflow,以为是不够好,改了依然如此,绝望中浪费了整整他妈的一个多小时。

public class Solution 
{
    public void solve(char[][] board) 
    {
        if(board.length == 0) return;
        boolean[][] moveVisit = new boolean[board.length][board[0].length];
        boolean[][] ok = new boolean[board.length][board[0].length];
        
        for(int i = 0; i < board.length;i++)
        {
            if(board[i][0] == 'O')
            {

                go(board,moveVisit,ok,i,0,true);
                moveVisit = new boolean[board.length][board[0].length];
            }
            if(board[i][board[0].length-1] == 'O')
            {

                go(board,moveVisit,ok,i,board[0].length-1,true);
                moveVisit = new boolean[board.length][board[0].length];
            }
        }
        
        for(int i = 1; i < board[0].length;i++)
        {
            if(board[0][i] == 'O')
            {

                go(board,moveVisit,ok,0,i,true);
                moveVisit = new boolean[board.length][board[0].length];
            }
            if(board[board.length-1][i]== 'O')
            {

                go(board,moveVisit,ok,board.length-1,i,true);

            }
        }
        

        
        
        for(int i = 1; i < board.length-1;i++)
        {
            for(int j = 1; j < board[0].length-1;j++)
            {
                if(board[i][j] == 'X') continue;
                
                if(!ok[i][j]) board[i][j] = 'X';
           
            }
        }
        
        return;
    }
    
    public void go(char[][] board, boolean[][] moveVisit, boolean[][] ok, int i, int j,boolean begin)
    {
        if(board[i][j] == 'X' || moveVisit[i][j]) return;
        if(!begin && (i == 0 || j == 0 || i == board.length-1 || j == board[0].length -1)) return;
        
        ok[i][j] = true;
        moveVisit[i][j] = true;
        
        if(i > 0 && board[i-1][j] == 'O') go(board,moveVisit,ok,i-1,j,false);

        
        
        if(j>0 && board[i][j-1] == 'O') go(board,moveVisit,ok,i,j-1,false);

        
        
        if(i < board.length-1 && board[i+1][j] == 'O') go(board,moveVisit,ok,i+1,j,false);

        

        if(j < board[0].length-1 && board[i][j+1] == 'O') go(board,moveVisit,ok,i,j+1,false);

        
        
        return;
   
    }
}
原文地址:https://www.cnblogs.com/reboot329/p/5880308.html