leetcode723

leetcode723
leetcode723
leetcode723
当前状态清完之后如果还有满足条件的,还需要继续清理。因此需要递归。
记录需要清理的状态,然后清理,用一个flag进行状态标识,决定是否需要继续进行递归清理

public class test {
    public int[][] candyCrush(int[][] board){
        if(board == null || board.length == 0 || board[0].length == 0){
            return board;
        }

        boolean todo = false;
        int m = board.length;
        int n = board[0].length;
        for(int i=0; i<m; i++){
            for(int j=0; j<n-2; j++){
                int val = Math.abs(board[i][j]);
                if(val!=0 && val==Math.abs(board[i][j+1]) && val==Math.abs(board[i][j+2])){
                    todo = true;
                    board[i][j] = board[i][j+1] = board[i][j+2] = -val;
                }
            }
        }

        for(int j=0; j<n; j++){
            for(int i=0; i<m-2; i++){
                int val = Math.abs(board[i][j]);
                if(val!=0 && val==Math.abs(board[i+1][j]) && val==Math.abs(board[i+2][j])){
                    todo = true;
                    board[i][j] = board[i+1][j] = board[i+2][j] = -val;
                }
            }
        }

        for(int j=0; j<n; j++){
            int br = m-1;
            for(int i=m-1; i>=0; i--){
                if(board[i][j]>0){
                    board[br--][j] = board[i][j];
                }
            }
            while(br>=0){
                board[br--][j] = 0;
            }
        }

        return todo ? candyCrush(board) : board;
    }
}
上一篇:2021-07-31


下一篇:Java实现三子棋小游戏