zoukankan      html  css  js  c++  java
  • LeetCode-N-Queens

    The n-queens puzzle is the problem of placing n queens on an nn 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.."]
    ]
    class Solution {
    public:
        int check(int* X,int k){
    		for(int i=0;i<k;i++){
    			if(X[i]==X[k]||abs(X[i]-X[k])==abs(i-k))return -1;
    		}
    		return 0;
    	}
    	vector<vector<string> > solveNQueens(int n) {
    		// Start typing your C/C++ solution below
    		// DO NOT write int main() function
    		vector<vector<string> > ret;
    		int* X=new int[n+1];
    		X[0]=-1;
    		int j=0;
    		while(j>=0)
    		{
    			X[j]++;
    			if(X[j]==n)
    			{
    				j--;
    				continue;
    			}
    			if(check(X,j)<0)
    			{
    					continue;
    			}
    			else
    			{
    				j++;
    				if(j==n){
    					vector<string> result;
    					for(int i=0;i<n;i++){
    						string s;
    						s.resize(n,'.');
    						s[X[i]]='Q';
    						result.push_back(s);
    					}
    					ret.push_back(result);
    					j--;
    				}
    				else
    				{
    					X[j]=-1;
    				}
    			}
    		}
    		delete X;
    		return ret;
    	}
    };
    

  • 相关阅读:
    【leetcode】反转字符串
    【leetcode】反转字符串 II
    053-669
    053-668
    053-667
    053-666
    053-665
    053-664
    053-663
    053-662
  • 原文地址:https://www.cnblogs.com/superzrx/p/3320608.html
Copyright © 2011-2022 走看看