【IT面试题005】八皇后
/* 8皇后 */ #include "stdafx.h" #include <iostream> #include <string> #include <vector> using namespace std; const int MAX_ELEMENT = 1000; int solution[MAX_ELEMENT]; bool columnHasChess[MAX_ELEMENT]; bool addDialogHasChess[MAX_ELEMENT]; bool subDialogHasChess[MAX_ELEMENT]; int gN; //行数 int gSolCount; void PrintSolution() { for (int i = 0;i < gN;i++) { cout << solution[i] << " "; } cout << endl; } //check 皇后是否能放在[row,col] bool check(int row,int col) { if (columnHasChess[col]) { return false; } if (addDialogHasChess[row + col]) { return false; } if (subDialogHasChess[row - col + gN]) { return false; } return true; } void Go(int row) { if (row == gN) { gSolCount ++; PrintSolution(); return; } //第row行选择那一列呢 for (int i = 0;i < gN;i++) { if (check(row,i)) { columnHasChess[i] = true; addDialogHasChess[i + row] = true; subDialogHasChess[row - i + gN] = true; solution[row] = i; Go(row + 1); columnHasChess[i] = false; addDialogHasChess[i + row] = false; subDialogHasChess[row - i + gN] = false; } } } int _tmain(int argc, _TCHAR* argv[]) { gN = 8; gSolCount = 0; memset(columnHasChess,0,sizeof(columnHasChess)); memset(addDialogHasChess,0,sizeof(addDialogHasChess)); memset(subDialogHasChess,0,sizeof(subDialogHasChess)); Go(0); cout << gSolCount << endl; }
posted on 2011-06-04 19:25 speedmancs 阅读(221) 评论(0) 编辑 收藏 举报