N-Queens II (Java)

来源:互联网 发布:淘宝老客户短信模板 编辑:程序博客网 时间:2024/05/17 15:02

Follow up for N-Queens problem.

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


八皇后问题:所有皇后所在行、列、斜线上不能有其他皇后出现。

用回溯法做,枚举第一行皇后可以在的所有位置,根据所在位置推出第二个皇后所在位置,以此类推,当推到最后一个后,就count+1。在推导过程中,如果遇到非法位置,则回溯到上一层。所以只有到达最后一行的放置方法才可以使count + 1。

用一维数组下标表示行,值表示列。

斜线判断方法:行坐标相减,列坐标相减,如果相等或负相等(最好用两个的绝对值, 比如出现[1,2]和[2,1])则在同一斜线上。

Source

public class Solution {int count = 0;    public int totalNQueens(int n) {        if(n == 0) return 0;    int[] col = new int[n];                backtrack(n, 0, col);        return count;    }    public void backtrack(int n, int row, int[] col){    if(row == n){    count += 1;    return;    }    for(int i = 0; i < n; i++){    col[row] = i;  //第row行放在i的位置上   枚举i的位置        if(isValid(row, col))    backtrack(n, row + 1, col);    }    }    public boolean isValid(int row, int[] col){    for(int i = 0; i < row; i++){ //检查已经放置的是否有效 注意end是row - 1    if(col[row] == col[i] || Math.abs(col[row] - col[i]) == row - i)  //同一斜线上的点有的性质:绝对值列值相减==行值相减    return false;    }    return true;    }}


Test

    public static void main(String[] args){        int n = 4;    System.out.println(new Solution().totalNQueens(n));    }


0 0