close
C++ 遇見皇后(八皇后問題)
有玩過西洋棋就知道,除了直的和橫的可以吃,斜的也是可以~~
皇后的能力就是吃斜的,沒限定一次走幾格,萬一和敵人的皇后在斜邊上碰面,另一方就是被吃掉的下場。
那咱們就來寫個程式,寫出共有幾種安全的可能
輸入說明 :
輸入之資料格式,一列資料代表一筆測資。每一列中,共有三個整數,第一個整數 N(3<N<9) 表示是 NxN 大小的棋盤,第二個整數 x (0~N-1) 及第三個整數 y (0~N-1) 用來標示給定的皇后位置。每一個整數之間以空白字元分隔。測資可能有多筆,請繼續讀取到沒有資料為止。
輸出說明 :
對於每一筆測資,如果可以把所有 N 只皇后都擺上去的話,請輸出 YES ,並在後面括號輸出所有合法的擺放方式數;如果沒辦法的話,請輸出 NO ,每一個測試範例的結果輸出一行。
範例 :
輸入範例 |
輸出範例 |
4 0 0 |
NO |
題目來源:https://e-tutor.itsa.org.tw/e-Tutor/mod/programming/view.php?a=10982
程式碼:
- #include <iostream>
- #include <vector>
- using namespace std;
- bool findqueen(vector<vector<bool> >& vbo, int x, int y)
- {
- for (int c = x - 1; c >= 0; --c) if (vbo[c][y]) return true;
- for (int c = x + 1; c < vbo.size(); ++c) if (vbo[c][y]) return true;
- for (int c = y - 1; c >= 0; --c) if (vbo[x][c]) return true;
- for (int c = y + 1; c < vbo[x].size(); ++c) if (vbo[x][c]) return true;
- for (int c = x + 1, d = y + 1; c < vbo.size() && d < vbo[x].size(); ++c, ++d) if (vbo[c][d]) return true;
- for (int c = x + 1, d = y - 1; c < vbo.size() && d >= 0; ++c, --d) if (vbo[c][d]) return true;
- for (int c = x - 1, d = y + 1; c >= 0 && d < vbo[x].size(); --c, ++d) if (vbo[c][d]) return true;
- for (int c = x - 1, d = y - 1; c >= 0 && d >= 0; --c, --d) if (vbo[c][d]) return true;
- return false;
- }
- void BT(vector<vector<bool> >& vbo, int& count, int row, int special)
- {
- if (row == vbo.size())
- {
- ++count;
- return;
- }
- if (row == special)
- {
- BT(vbo, count, row + 1, special);
- return;
- }
- for (int c = 0; c < vbo.size(); c++)
- {
- if (!findqueen(vbo, row, c))
- {
- vbo[row][c] = true;
- BT(vbo, count, row + 1, special);
- vbo[row][c] = false;
- }
- }
- }
- int main()
- {
- int num;
- while (cin >> num)
- {
- int x, y;
- cin >> x >> y;
- vector<vector<bool> > vbo(num, vector<bool>(num, false));
- vbo[x][y] = true;
- int count = 0;
- BT(vbo, count, 0, x);
- if (count == 0)
- {
- cout << "NO" << endl;
- }
- else
- {
- cout << "YES(" << count << ")" << endl;
- }
- }
- return 0;
- }
全站熱搜