leetcode N-Queens
2014-10-21 22:08
369 查看
任然是NP问题,解决此类问题主要思想就是递归,
就是用一个循环去枚举当前所有情况,然后把元素加入,递归,再把元素移除
代码1 提示
Output Limit Exceeded 输出结果中有重复的
Accepted 代码 参考 http://www.cnblogs.com/TenosDoIt/p/3801621.html
就是用一个循环去枚举当前所有情况,然后把元素加入,递归,再把元素移除
代码1 提示
Output Limit Exceeded 输出结果中有重复的
class Solution { public: void solveNQueensHelper(vector<vector<string> > &result, vector<string> &tempResult, vector<bool> &flagRow, vector<bool> &flagCol, int &num, int n) { if(num==n) { result.push_back(tempResult); return ; } for(int i = 0; i < n; ++i) { if(flagRow[i]==false) continue; for(int j = 0; j < n; ++j) { if(flagCol[j]==false) continue; tempResult[i][j] = 'Q'; flagRow[i] = false; flagCol[j] = false; num++; solveNQueensHelper(result, tempResult, flagRow, flagCol, num, n); num--; flagRow[i] = true; flagCol[j] = true; tempResult[i][j] = '.'; } } return ; } vector<vector<string> > solveNQueens(int n) { vector<vector<string> > result; if(n==0) return result; vector<bool> flagRow(n, true); vector<bool> flagCol(n, true); vector<string> tempResult; for(int i = 0; i < n; ++i) { string str = ""; for(int j = 0; j < n; ++j) str += '.'; tempResult.push_back(str); } int num = 0; solveNQueensHelper(result, tempResult, flagRow, flagCol, num, n); return result; } };
Accepted 代码 参考 http://www.cnblogs.com/TenosDoIt/p/3801621.html
class Solution { public: vector<vector<string> > solveNQueens(int n) { vector<vector<string> > result; if(n==0) return result; vector<int> state(n,-1); solveNQueensHelper(result, state, 0); return result; } void solveNQueensHelper(vector<vector<string> > &result, vector<int> &state, int row) { int n = state.size(); if(row==n) { vector<string> temp(n, string(n, '.')); for(int i = 0; i < n; ++i) { temp[i][state[i]] = 'Q'; } result.push_back(temp); return ; } for(int col = 0; col < n; ++col) { if(isValid(state, row, col)) { state[row] = col; solveNQueensHelper(result, state, row+1); state[row] = -1; } } return ; } bool isValid(vector<int> &state, int row, int col) { for(int i = 0; i < row; ++i) if(state[i]==col || abs(row - i) == abs(col - state[i])) return false; return true; } };
相关文章推荐
- LeetCode---N-Queens
- LeetCode N-Queens
- [LeetCode] N-Queens II N皇后问题之二
- Leetcode -- N-Queens
- LeetCode---N-Queens
- leetcode 51. N-Queens
- [LeetCode] N-Queens
- N-Queens -- LeetCode
- LeetCode 51. N-Queens
- leetcode笔记:N-Queens
- LeetCode-N-Queens
- leetcode--N-Queens
- leetcode-51-N-Queens
- leetcode n-queens
- LeetCode之N-Queens
- LeetCode 51. N-Queens
- LeetCode N-Queens
- N-Queens N皇后问题@LeetCode
- leetcode: N-Queens
- [leetcode] N-Queens