52. N-Queens II

题目:

解答:

使用题51的解法,但是不需要保存记录了。

代码:

class Solution {
public:
    bool CheckOK(vector<string>& panel, int row, int col,int n){
        for(int i = 0;i < row; ++i)
            if(panel[i][col] == 'Q')
                return false;
        for(int i = row - 1;i >= 0; --i){
            if(col + row - i < n && panel[i][col+row-i] == 'Q')
                return false;
            if(col - row + i >= 0 && panel[i][col-row+i] == 'Q')
                return false;
        }
        return true;
    }
	int totalNQueens(int n) {
			string line(n, '.');
			vector<string> chesspanel(n, line);
			int row = 0, col = 0;
            if(n == 1){
                return 1;
            }
            int cnt = 0;
			while(true){
				while(row != n){
                    // 遍历寻找每行的可放置位置
					while(col != n){
						if(CheckOK(chesspanel, row, col, n)){
							chesspanel[row][col] = 'Q';
							++row;
							col = 0;
							break;
						}
						++col;
					}
					if(col == n){
						while(row > 0){
							bool updateOK = false;
							for(int i = 0;i < n; ++i){
								if(chesspanel[row-1][i] == 'Q'){
									if(i != n - 1){
                                        // 如果没有合适的,在将上一行的位置右移一个位置点
										chesspanel[row-1][i] = '.';
										col = i + 1;
										updateOK = true;
										--row;
										break;
									}else{
                                        // 如果上一行已经到了最边缘,递归向上求解,如果到顶层,结束
										chesspanel[row-1][i] = '.';
										col = 0;
										--row;
										if(row == 0)
											return cnt;
										break;
									}
								}
							}
							if(updateOK)
								break;
						}
					}
				}
				++cnt;
				row--;
                //寻找下一个位置点
				for(int i = 0;i < n; ++i)
					if(chesspanel[row][i] == 'Q'){
						chesspanel[row][i] = '.';
						col = i + 1;
						break;
					}
			}
			return cnt;
		}
};

更新会同步在我的网站更新(https://zergzerg.cn/notes/webnotes/leetcode/index.html)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值