TA的每日心情 | 开心 2014-6-18 08:29 |
---|
签到天数: 14 天 [LV.3]偶尔看看II
滴水大师
 
- 积分
- 2345
|
题目
解决代码及点评
- <pre code_snippet_id="91880" snippet_file_name="blog_20131202_1_2646179" class="cpp" name="code"></pre><pre code_snippet_id="91880" snippet_file_name="blog_20131202_1_2646179" class="cpp" name="code"><pre code_snippet_id="91880" snippet_file_name="blog_20131202_1_2646179" class="cpp" name="code"><pre code_snippet_id="91880" snippet_file_name="blog_20131202_1_2646179" class="cpp" name="code"><pre code_snippet_id="91880" snippet_file_name="blog_20131202_1_2646179" class="cpp" name="code">/************************************************************************/
- /*
- 74. 八皇后问题。
- 在一个8×8的国际象棋棋盘上放入8个皇后,且这八个皇后互不相吃,即这8个皇后的任意两个都不在同一行、同一列及同一斜线上。
- 编程序找出所有放法。
- 其中一个答案是:(*表示皇后)
- 提示:
- 1) 可用一维数组(8个元素)存贮上述答案:
- 1 5 8 6 3 7 2 4
- 2) 为了使问题简单,可先做5×5棋盘上的5皇后问题。
- */
- /************************************************************************/
- #include <stdio.h>
- #include <stdlib.h>
- static int num=0;
- bool IsSafe(int x,int y,int queenarr[])
- {
- for (int i=0;i<x;i++)
- {
- if (y==queenarr)
- {
- return false;
- }
- }
- for (int i=0;i<x;i++)
- {
- if (x-y==i-queenarr||x+y==queenarr+i)//斜着
- {
- return false;
- }
- }
- return true;
- }
- bool Putit(int row,int queenarr[])
- { bool isfound=false;
- if (row==8)
- {
- isfound=true;
- for (int i=0;i<8;i++)
- {
- printf("%3d",queenarr);
- }
- printf("\n");
- num++;
- }
- else
- {
- int i=0;
- for (;i<8;i++)
- {
- if (!IsSafe(row,i,queenarr))
- {
- continue;
- }
- else
- {
- queenarr[row]=i;
- }
- isfound=Putit(row+1,queenarr);
- if (!isfound)
- {
- queenarr[row]=-1;
- }
- }
- return isfound;
- }
- }
- void main()
- {
- int queenarr[8];
- for (int i=0;i<8;i++)
- {
- queenarr=-1;
- }
- bool flag= Putit(0,queenarr);
- printf("共有%d排种法",num);
- system("pause");
- }</pre><br><br><br></pre></pre></pre>
|
|