[leetcode] N-Queens

来源:互联网 发布:模拟汽车软件 国外 编辑:程序博客网 时间:2024/06/06 02:35

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.."]]
思路:深度搜索,属于经典问题了,定义两个数组,行数组和列数组,行数组用来存储该行摆放位置,列数组用来存储该列是否已经摆放过了,本代码参考了大神的代码

代码:

class Solution {    int row[1000],col[1000];    vector<vector<string> > res;public:    vector<vector<string> > solveNQueens(int n) {        res.clear();        dfs(0,n);        return res;    }    void dfs(int step, int n){        int i,j;        if(step==n){            vector<string> rows;            for(i=0;i<n;i++){                string temp(n,'.');                temp[row[i]]='Q';                rows.push_back(temp);            }            res.push_back(rows);        }        for(i=0;i<n;i++){            if(col[i]==0){                for(j=0;j<step;j++){                    if(abs(j-step)==abs(i-row[j])) break;//列之间的距离与行之间的距离相等;                }                if(j==step){                    row[step]=i;                    col[i]=1;                    dfs(step+1,n);                    row[step]=0;                    col[i]=0;                }            }        }    }};



0 0
原创粉丝点击