|
楼主 |
发表于 2018-9-28 20:58:35
|
显示全部楼层
- int Count=0; //方法计数
- int FirstRow=0; //第一行皇后位置
- int RowIsOk=0;
- int IsNotDanger(int row,int col)
- {
- if(chess[row][col]==-1)return 0; //当前位置
- for(int m=0;m<row;m++)
- if(chess[m][col]==1)return 0; //列
- for(int m=row-1,n=col-1;m>=0&&n>=0;m--,n--)
- if(chess[m][n]==1)return 0; //左上角
- for(int m=row-1,n=col+1;m>=0&&n<N;m--,n++)
- if(chess[m][n]==1)return 0; //右上角
- for(int m=row+1,n=col-1;m<N&&n>=0;m++,n--)
- if(chess[m][n]==1)return 0; //左下角
- for(int m=row+1,n=col+1;m<N&&n<N;m++,n++)
- if(chess[m][n]==1)return 0; //左上角
- return 1;
- }
- void Queen2(int row)
- {
- if(FirstRow==N)return;
- RowIsOk=0;
- if(row==N)
- {
- Count++;
- printf("第 %d 种:\n",Count);
- for(int i=0;i<N;i++)
- {
- for(int j=0;j<N;j++)
- {
- if(chess[i][j]==1)
- printf("%d ",chess[i][j]);
- else printf("0 ");
- }
- cout<<endl;
- }
- for(int j=0;j<N;j++)
- if(chess[row-1][j]==1)chess[row-1][j]=-1;
- }
- else
- {
- for(int j=0;j<N;j++)
- if(IsNotDanger(row,j))
- {
- RowIsOk=1;
- chess[row][j]=1;
- Queen2(row+1);
- }
- if(!RowIsOk)
- {
- for(int j=0;j<N;j++)
- if(chess[row-1][j]==1)
- {
- chess[row-1][j]=-1;
- break;
- }
- for(int j=0;j<N;j++)chess[row][j]=0;
- if(row==1)FirstRow++;
- Queen2(row-1);
- }
- }
- }
- int main()
- {
- for(int i=0;i<N;i++)
- for(int j=0;j<N;j++)
- chess[i][j]=0;
- Queen2(0);
- return 0;
- }
复制代码
麻烦帮我看一下,谢谢!
N<10的时候一切正常,N>=10就计算不出来了。
N=9
|
-
N=10
-
N=8
|