您的位置:首页 > 编程语言

写了一个八皇后问题的代码

2010-11-02 18:38 246 查看
经典的问题,不过以前没有做过,今天动手写了一个,效率不是很高,但思想是有一点的,最主要是判断斜线的方法,用x+y和x-y来判断。
1: #include <iostream>


2: 


3: using namespace std;


4: #define N 8


5: 


6: void show(int A

)


7: {


8:     static int count = 0;


9:     cout << ++count << endl;


10:     for (int i = 0; i < N; i++)


11:     {


12:         for (int j = 0; j < N; j++)


13:         {


14:             if (A[i][j] == 1)


15:             {


16:                 cout << "W ";


17:             }


18:             else


19:             {


20:                 cout << "- ";


21:             }


22:         }


23:         cout << endl;


24:     }


25:     cout << endl;


26: }


27: 


28: bool check(int A

, int x, int y)


29: {


30:     int sum = x + y;


31:     int sub = x - y;


32:     for (int i = 0; i < N; i++)


33:     {


34:         if (x != i && A[i][y] == 1)


35:         {


36:             return false;


37:         }


38:         for (int j = 0; j < N; j++)


39:         {


40:             if (j == y)


41:             {


42:                 continue;


43:             }


44:             if (A[x][j] == 1)


45:             {


46:                 return false;


47:             }


48:             if (i + j == sum && A[i][j] == 1)


49:             {


50:                 return false;


51:             }


52:             if (i - j == sub && A[i][j] == 1)


53:             {


54:                 return false;


55:             }


56:         }


57:     }


58: 


59:     return true;


60: }


61: 


62: void putQueen(int A

, int row)


63: {


64:     if (row >= N)


65:     {


66:         show(A);


67:         return;


68:     }


69: 


70:     for (int i = 0; i < N; i++)


71:     {


72:         A[row][i] = 1;


73: 


74:         if (check(A, row, i) != false)


75:         {


76:             putQueen(A, row + 1);


77:         }


78: 


79:         A[row][i] = 0;


80:     }


81: 


82:     return;


83: }


84: 


85: void run(int x

)


86: {


87:      putQueen(x, 0);


88: }


89: 


90: int main()


91: {


92:     int X

= {0};


93:     run(X);


94:     system("pause");


95:     return 0;


96: }
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: