leetcode-51. N-Queens

The n-queens puzzle is the problem of placing n queens on an n×n chessboard such that no two queens attack each other.

Given an integer n, return all distinct solutions to the n-queens puzzle.

Each solution contains a distinct board configuration of the n-queens' placement, where 'Q' and '.' both indicate a queen and an empty space respectively.

For example,
There exist two distinct solutions to the 4-queens puzzle:

[
 [".Q..",  // Solution 1
  "...Q",
  "Q...",
  "..Q."],

 ["..Q.",  // Solution 2
  "Q...",
  "...Q",
  ".Q.."]
]

题意解析:

这道题是说,给出一个整数n,有n个皇后,棋盘大小n * n,请问有几种排列可以让皇后之间不互相攻击。

解题思路:

这道题可以很快地想到两个思路,一个是全排列,一个是回溯法。

下面是回溯法代码,代码总体比较简单,只要注意几个注意点,一个是回溯的时候,要把queens[row]的值清0;还有一个是要注意什么情况下会导致皇后可以互相攻击。我用的是逐行深度遍历,也可以写逐列的,道理是一样的。

public class Solution {
    
    private List> result;
    public List> solveNQueens(int n) {
        result = new ArrayList>();
        int[] queens = new int[n];//queens数组:queens[i] = j表示皇后在第i行第j列
        backTracking(queens, n, 0);
        return result;
    }
    public void backTracking(int[] queens, int n, int row){
        for(int col = 0; col < n; col++){
            if(check(queens, n, row, col)){
                queens[row] = col;
                if(row == n - 1){
                    resultAdd(queens, n);
                    queens[row] = 0;
                    return;
                }
                backTracking(queens, n, row + 1);
                queens[row] = 0;
            }
        }
    }
    public boolean check(int[] queens, int n, int row, int col){
        for(int i = 0; i < row; i++){
            //三种情况不成立:正斜线(q[i]-i=q[j]-j),反斜线(q[i]+i=q[j]+j),列相等,注意这里行是不可能相等的
            if(queens[i] == col || queens[i] + i == col + row || queens[i] - i == col - row){
                return false;
            }
        }
        return true;
    }
    public void resultAdd(int[] queens, int n){
        List res = new ArrayList();
        for(int i = 0; i < n; i++){
            String x = "";
            for(int j = 0; j < n; j++){
                if(j == queens[i]){
                    x += "Q";
                }else{
                    x += ".";
                }
            }
            res.add(x);
        }
        result.add(res);
    }
}


leetcode正在修复代码时间分布图。。只好过段时间再看了。希望还能想起来这件事。

你可能感兴趣的:(LeetCode题解)