LeetCode刷题笔记-52

LeetCode-51. N-Queens(Hard):

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 the number of distinct solutions to the n-queens puzzle.

Example:

Input: 4
Output: 2
Explanation: There are two distinct solutions to the 4-queens puzzle as shown below.
[
 [".Q..",  // Solution 1
  "...Q",
  "Q...",
  "..Q."],

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

我的解法:

52题是51题的简化,答案不用输出八皇后问题的解的排列,只需要输出解的个数。

由于51题是看了答案,52题决定自己做一下。不做不知道,一做就卧槽。对这个问题的解法有了更深刻的理解,其中51题答案没看懂的部分也看懂了。

       一共两个函数,totalNQueens中首先定义三个数组,分别记录列、左上到右下的斜排(2n-1排)、右上到左下的斜排(2n-1排)的占用情况。然后调用NQueens返回答案。NQueens中按行依次遍历,循环的方式(依次尝试)确定第一排皇后的位置,记录列和斜排的占用情况,当然行就不用记录了,因为是一行一行寻找皇后可能的安放位置,行是不冲突的。然后递归调用NQueens确定下一行皇后的位置(row+1),如果row == n,就代表之前从0到n-1的n行都找到了皇后的位置,那么就找到了一种可行的排列,ans++。因为是回溯问题,所以每一个递归结束后需要恢复状态(代码中for循环最后三行)。回溯问题的关键就在于状态的记录和恢复。

class Solution {
    public int totalNQueens(int n) {
        
        boolean[] col = new boolean[n];
        boolean[] topleftTobottomright = new boolean[2*n-1];
        boolean[] toprightTobottomleft = new boolean[2*n-1];
        
        int ans = 0;
        ans = NQueens(ans, n, 0, col, topleftTobottomright, toprightTobottomleft);
        return ans;
    }
    
    public int NQueens(int ans, int n, int row, boolean[] col, boolean[] tlTobr, boolean[] trTobl) {
		if(row == n) {
			ans = ans + 1;
			//System.out.println(ans); 
			return ans;  
		}
		for(int i = 0; i < n; i++) {
			if(col[i] || tlTobr[i+row] || trTobl[n-1 + row-i]) {
				continue;
			}			
            col[i] = true;
            tlTobr[i+row] = true;
            trTobl[n-1 + row-i] = true;
            ans = NQueens(ans, n, row+1, col, tlTobr, trTobl);            
            col[i] = false;
            tlTobr[i+row] = false;
            trTobl[n-1 + row-i] = false;            
		}
		return ans;
	}
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值