51. N-Queens

题目:

解答:

使用深度搜索寻找出所有符合要求的皇后排序位置。代码如下:

  • CheckOK: 用于判定在第row行col列放置皇后,是否会与之前的有冲突(之前的会维护为合法的皇后布局)
  • while(row != n):这层循环用于获取在当前布局和当前row,col下的计算下一个合法的n皇后布局
  • 最后面的for循环:前面已经将合法的一个n皇后布局存入,然后将最后一行的皇后位置右移一个单位,重新进入循环计算下一个合法的n皇后布局。
  • 终止条件:在二层while循环的if(row == 0)这里return,此处含义是,此时已经将n皇后的推算到第一个皇后右移到了最右边+1,仍然没有合适的匹配布局,则计算结束。

代码:

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;
    }
		vector<vector<string>> solveNQueens(int n) {
			string line(n, '.');
			vector<string> chesspanel(n, line);
			int row = 0, col = 0;
			vector<vector<string>> result;
            if(n == 1){
                chesspanel[0][0] = 'Q';
                result.push_back(chesspanel);
                return result;
            }
                
			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 result;
										break;
									}
								}
							}
							if(updateOK)
								break;
						}
					}
				}
				result.push_back(chesspanel);
				row--;
                //寻找下一个位置点
				for(int i = 0;i < n; ++i)
					if(chesspanel[row][i] == 'Q'){
						chesspanel[row][i] = '.';
						col = i + 1;
						break;
					}
			}
			return result;
		}
};

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值