51. N皇后
Posted zouma
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了51. N皇后相关的知识,希望对你有一定的参考价值。
待完善
1 class Solution 2 public: 3 4 int* queens; 5 int* rows; 6 int* dales; 7 int* hills; 8 int m = 0; 9 vector<vector<string>> res; 10 bool attcked(int row,int col) 11 12 int res = rows[col] + dales[row+col] + hills[row-col+m]; 13 if (res) 14 return true; 15 else 16 return false; 17 18 void put(int row,int col) 19 20 queens[row] = col; 21 rows[col] = 1; 22 dales[row + col] = 1; 23 hills[row - col + m] = 1; 24 25 void remove(int row, int col) 26 27 queens[row] = 0; 28 rows[col] = 0; 29 dales[row + col] = 0; 30 hills[row - col + m] = 0; 31 32 void getsolution(int row,int col) 33 34 vector<string> tempres; 35 for (int i = 0; i < m; i++) 36 37 int index = queens[i]; 38 string temp; 39 for (int j = 0; j < index; j++) 40 41 temp.append("."); 42 43 temp.append("Q"); 44 for (int j = 0; j < m - index - 1; j++) 45 temp.append("."); 46 tempres.push_back(temp); 47 48 res.push_back(tempres); 49 50 void backtrack(int row) 51 52 for(int col=0;col<m;col++) 53 54 if (attcked(row, col) == false) 55 56 put(row, col); 57 if (row + 1 == m) 58 getsolution(row,col); 59 else 60 backtrack(row + 1); 61 remove(row, col); 62 63 64 65 vector<vector<string>> solveNQueens(int n) 66 m = n; 67 queens=new int[n]; 68 rows = new int[n]; 69 for (int i = 0; i < n; i++) 70 71 queens[i] = 0; 72 rows[i] = 0; 73 74 dales=new int[2*n]; 75 hills=new int[2*n]; 76 for (int i = 0; i < 2*n; i++) 77 78 dales[i] = 0; 79 hills[i] = 0; 80 81 backtrack(0); 82 return res; 83 84 ;
以上是关于51. N皇后的主要内容,如果未能解决你的问题,请参考以下文章