LeetCode --- 52. N皇后 II

解法一:

class Solution {
    private int ways;
    public int totalNQueens(int n) {
        // 声明一个长度为n的数组用来代表 第n行棋子是在第result[n]列
        int[] result = new int [n];
        ways = 0;
        place(0, n, result);
        return ways;
    }
    
    // n 皇后问题 row代表计算到了到第row行
    private void place(int row, int n, int[] result){
        if (row == n){
            ways++;
            return;
        }
        // 若不是第n行 则说明需要继续判断该行棋子应该在那一列
        for (int column = 0; column < n; column++){
            // 判断第row行 放置在column列的棋子是否满足要求
            if (isValid(row, column, result)){
                result[row] = column;
                // 递归判断下一行的情况
                place(row + 1, n, result);
            }
            // 不满足要求 回溯下一列 对应操作column++
        }
    }
    
    // row代表行数 column代表列数 result代表满足规则的棋子在第n行中的位置
    private boolean isValid(int row, int col, int[] result){
        // 判断棋子的位置是否正确 不正确返回false
        for (int i = 0; i < row; i++){        
        	// 第col列已经有皇后
        	if (result[i] == col) return false;
        	// 第i行的皇后跟第row行第col列格子处在同一斜线上
        	if (row - i == Math.abs(col - result[i])) return false;
        }
    	return true;
    }
}

解法二:

class Solution {
	// 标记着某一列是否有皇后
	boolean[] cols;
	// 标记着某一斜线上是否有皇后(左上角 -> 右下角)
	boolean[] leftTop;
	// 标记着某一斜线上是否有皇后(右上角 -> 左下角)
	boolean[] rightTop;
	
    private int ways;
    
    public int totalNQueens(int n) {
        cols = new boolean[n];
        leftTop = new boolean[(n << 1) - 1];
        rightTop = new boolean[(n << 1) - 1];
        ways = 0;
   		place(0);
   		return ways;        
    }
    // 从第row行开始摆放皇后
	private void place(int row) {
    	if (row == cols.length) {
			ways++;
        	return;
    	}
    	for (int col = 0; col < cols.length; col++) {
        	if (cols[col]) continue;
        	int ltIndex = row - col + cols.length - 1;
        	if (leftTop[ltIndex]) continue;
        	int rtIndex = row + col;
        	if (rightTop[rtIndex]) continue;
        	cols[col] = leftTop[ltIndex] = rightTop[rtIndex] = true;
        	place(row + 1);
        	cols[col] = leftTop[ltIndex] = rightTop[rtIndex] = false;
     	}
	}
}
发布了188 篇原创文章 · 获赞 19 · 访问量 8万+

猜你喜欢

转载自blog.csdn.net/songzhuo1991/article/details/104127329