N-Queens II

原题:

Follow up for N-Queens problem.

Now, instead outputting board configurations, return the total number of distinct solutions.

回溯法代码:

public class Solution {
    boolean able_place(boolean[][] matrix, int place_row, int place_col){
        for(int row = place_row-1; row >= 0; --row){
        	if(matrix[row][place_col] == true) return false;
        }
        for(int row = place_row-1,col = place_col-1; row >= 0 && col >= 0; --row,--col){
        	if(matrix[row][col] == true) return false;
        }
        for(int row = place_row-1,col = place_col+1; row >= 0 && col < matrix[0].length; --row,++col){
        	if(matrix[row][col] == true) return false;
        }
		return true;
    }
    
    int NQueens(int n, int place_row, boolean[][] matrix){
    	if(place_row >= matrix.length) return 0;
        int count = 0;
        for(int j = 0; j < matrix[0].length; ++j){
            if(able_place(matrix,place_row,j)){
            	matrix[place_row][j] = true;
                if(place_row == matrix.length-1){
                	return 1;
                }
                count = count + NQueens(n,place_row+1,matrix);
                matrix[place_row][j] = false;
            }
        }
        return count;
    }
    
    public int totalNQueens(int n) {
        return NQueens(n,0,new boolean[n][n]);
    }
}

感觉用分治算法优化不了啊,之前写错过一次,还以为下面这样写能优化速率呢

void adjust_matrix(int place_row, int place_col, boolean[][]matrix, boolean place){
	        for(int row = place_row; row < matrix.length; ++row){
	            matrix[row][place_col] = place;
	        }
	        for(int col = place_col+1, row = place_row+1; col < matrix[0].length && row < matrix.length; ++col,++row){
	            matrix[row][col] = place;
	        }
	        for(int col = place_col-1, row = place_row+1; col >=0 && row < matrix.length; --col,++row){
	            matrix[row][col] = place;
	        }
	    }
	    
	    int NQueens(int n, int place_row, boolean[][] matrix){
	    	if(place_row >= matrix.length) return 0;
	        int count = 0;
	        for(int j = 0; j < matrix[0].length; ++j){
	            if(!matrix[place_row][j]){
	                adjust_matrix(place_row,j,matrix,true);
	                if(place_row == matrix.length-1){
	                	return 1;
	                }
	                count = count + NQueens(n,place_row+1,matrix);
//	                count = 1 + NQueens(n,place_row+1,matrix);
	                adjust_matrix(place_row,j,matrix,false);
	            }
	        }
	        return count;
	    }
	    
	    public int totalNQueens(int n) {
	        return NQueens(n,0,new boolean[n][n]);
	    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值