[LeetCode] N-Queen N 황후.

2120 단어 LeetCode
문제1: 8황후 문제, 해결 방향과 코드
관련 질문 2:
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:
4
[
 [".Q..",  // Solution 1
  "...Q",
  "Q...",
  "..Q."],

 ["..Q.",  // Solution 2
  "Q...",
  "...Q",
  ".Q.."]
]
본 문제의 사고방식은 8황후 문제의 사고방식과 완전히 같다.
코드는 다음과 같습니다.
class Solution {
public:
vector<vector<string> > solveNQueens(int n) {
    
    vector<string> sol;
    vector<vector<string>> sols;
    solveNQueensUtil(n, 0, sol, sols);
    
    return sols;
}

//     N-Queen  
//      ,            
void solveNQueensUtil(int n, int row, vector<string> sol, vector<vector<string>>& sols) {
    
    if(row==n)
    {
        sols.push_back(sol);
        return;
    }
    
    for(int i=0;i<n;i++)
    {
        string str(n, '.');
        str[i]='Q';
        sol.push_back(str);
        
        if(isValid(sol, row, i))
            solveNQueensUtil(n, row+1, sol, sols);
        
        sol.pop_back();
    }
    
}
    
bool isValid(vector<string> &cur, int row, int col)
{
	int count = 0;

    //  
    for(int i = 0; i <= row; i++)
	{
        if(cur[i][col] == 'Q')
			count++;
		if(count>1) return false;
	}

	count = 0;

    //    
    for(int i = row, j=col; i >= 0 && j >= 0; i--,j--)
	{
        if(cur[i][j] == 'Q')
			count++;
		if(count>1) return false;
	}

	count=0;

    //    
    for(int i = row, j=col; i >= 0 && j < cur[0].size(); i--,j++)
	{
        if(cur[i][j] == 'Q')
			count++;
		if(count>1) return false;
	}

    return true;
}
};

좋은 웹페이지 즐겨찾기