19.2.8 [LeetCode 51] N-Queens
阿新 • • 發佈:2019-02-08
vector class ret str public alt color spl contains
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.
Example:
Input: 4
Output: [
[".Q..", // Solution 1
"...Q",
"Q...",
"..Q."],
["..Q.", // Solution 2
"Q...",
"...Q",
".Q.."]
]
Explanation: There exist two distinct solutions to the 4-queens puzzle as shown above.
首先用了最直白最經典的方法,還是學計概的時候寫過的
1 class Solution { 2 public: 3 bool valid(vector<string>a, int x, int y,int n) { 4 int i = 1; 5 while (x - i >= 0 && y - i >= 0) { 6 if (a[x - i][y - i] == ‘Q‘)return false; 7 i++; 8 } 9 i = 1; 10 whileView Code(x-i>=0&&y+i<=n) { 11 if (a[x - i][y + i] == ‘Q‘)return false; 12 i++; 13 } 14 return true; 15 } 16 void build(vector<vector<string>>&ans,vector<string>now, int n, vector<bool>line,int row) { 17 if (row >= n) { 18 ans.push_back(now); 19 return; 20 } 21 for(int i=0;i<n;i++) 22 if (!line[i] && valid(now, row, i, n)) { 23 now[row][i] = ‘Q‘; 24 line[i] = true; 25 build(ans, now, n, line, row + 1); 26 line[i] = false; 27 now[row][i] = ‘.‘; 28 } 29 } 30 vector<vector<string>> solveNQueens(int n) { 31 vector<vector<string>>ans; 32 string str = ""; 33 for (int i = 0; i < n; i++)str += ‘.‘; 34 vector<string>now(n, str); 35 vector<bool>line(n, false); 36 build(ans, now, n, line, 0); 37 return ans; 38 } 39 };
當然非常慢
然後看了別人的帖子想起來還有用一維數組存圖的方法,但是還是很慢,用的方法和別人完全一樣但是慢了很多是怎麽回事……
1 class Solution { 2 public: 3 bool valid(vector<int>a, int x, int y) { 4 for (int i = 0; i < x; i++) 5 if (y == a[i] || abs(a[i] - y) == x - i) 6 return false; 7 return true; 8 } 9 void build(vector<vector<string>>&ans,vector<int>&now,int row) { 10 int n = now.size(); 11 if (row == n) { 12 vector<string>res(n, string(n,‘.‘)); 13 for (int i = 0; i < n; i++) 14 res[i][now[i]] = ‘Q‘; 15 ans.push_back(res); 16 return; 17 } 18 for(int i=0;i<n;i++) 19 if (valid(now, row, i)) { 20 now[row] = i; 21 build(ans, now, row + 1); 22 } 23 } 24 vector<vector<string>> solveNQueens(int n) { 25 vector<vector<string>>ans; 26 vector<int>pos(n, -1); 27 build(ans,pos, 0); 28 return ans; 29 } 30 };View Code
19.2.8 [LeetCode 51] N-Queens