• 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.."]
    ]
    
    

    解析

    • 经典dfs+回溯方法
    // add 51. N-Queens
    class Solution_51 {
    public:
    	bool isValid(vector<string> &vec,int i,int j)
    	{
    		//判断当前放置位置(i,j)是否合理
    		for (int row = 0; row < i;row++) //判断同一列列
    		{
    			if (vec[row][j]=='Q') // vec[i][j]
    			{
    				return false;
    			}
    		}
    		//判断对角线45°
    		for (int row = i-1, col = j-1; row >= 0 && col>=0;row--,col--)
    		{
    			if (vec[row][col] == 'Q')
    			{
    				return false;
    			}
    		}
    		//判断对角线135%
    		for (int row = i-1, col = j + 1; row >= 0 && col < vec.size();row--,col++) //写法: row >= 0, col < vec.size() 错误
    		{
    			if (vec[row][col] == 'Q')
    			{
    				return false;
    			}
    		}
    		return true;
    	}
    
    	void solveNQueensHelp(vector<vector<string>> &vecs,vector<string> &vec,int row,int n)
    	{
    		if (row==n)
    		{
    			vecs.push_back(vec);
    			return;
    		}
    
    		for (int col = 0; col < n;col++)
    		{
    			if (isValid(vec,row,col))
    			{
    				vec[row][col] = 'Q';
    				solveNQueensHelp(vecs, vec, row + 1, n);
    				vec[row][col] = '.';
    			}
    		}
    		return;
    	}
    
    	vector<vector<string>> solveNQueens(int n) {
    
    		vector<string> vec(n,string(n,'.')); 
    
    		vector<vector<string> > vecs; //所有解
    
    		solveNQueensHelp(vecs,vec,0,n);
    		
    		return vecs;
    	}
    };
    
    

    题目来源

  • 相关阅读:
    JSP实验四
    servlet应用
    SWPU电子邮件页面
    Java Web基础
    软件工程课程总结
    Beta-星期五
    个人作业-Alpha项目测试
    第三次作业
    学期总结-西北师范大学-18计师班助教牛百泉
    Java学习计划
  • 原文地址:https://www.cnblogs.com/ranjiewen/p/8548372.html
Copyright © 2020-2023  润新知