EightQueens.zip

  • PUDN用户
    了解作者
  • C++
    开发工具
  • 1KB
    文件大小
  • zip
    文件格式
  • 0
    收藏次数
  • 1 积分
    下载积分
  • 2
    下载次数
  • 2009-11-25 12:27
    上传日期
Eight Queens solution. There is a simple task to place 8 queens on one board. Each of them doesn t have to kill others.
EightQueens.zip
  • Eight+queens.cpp
    3KB
内容介绍
#include <iostream> #include <time.h> using namespace std; struct place { int x,y; }; void print(int [][8], int); void cleanUp(int [][8], int); int placeQueen(int [][8], int, int); void main() { int counter=1, x=0,y=0,z=0; place Q1,Q2,Q3,Q4,Q5,Q6,Q7,Q8; char stop='y'; int field[8][8]={{0},{0}}; while (stop!='n') { cleanUp(field,8); srand(time(0)); srand(rand()%8); y=rand()/7; field[x][y]=-1; counter=1; Q1.x=x; Q1.y=y; for (int i=0; i<8; i++) for (int j=0; j<8; j++) { if (placeQueen(field,i,j)==1) { counter++; field[i][j]=-1; switch (counter) { case 2: Q2.x=i; Q2.y=j; break; case 3: Q3.x=i; Q3.y=j; break; case 4: Q4.x=i; Q4.y=j; break; case 5: Q5.x=i; Q5.y=j; break; case 6: Q6.x=i; Q6.y=j; break; case 7: Q7.x=i; Q7.y=j; break; case 8: Q8.x=i; Q8.y=j; break; default: break; } } } z++; srand(time(0)); x=rand()%8; system("cls"); cout<<"Repeat #"<<z<<endl; cout<<"Row #"<<x<<endl; cout<<"Column #"<<y<<endl; cout<<"Counter = "<<counter<<endl; if (counter==8) { field[Q1.x][Q1.y]=1; field[Q2.x][Q2.y]=2; field[Q3.x][Q3.y]=3; field[Q4.x][Q4.y]=4; field[Q5.x][Q5.y]=5; field[Q6.x][Q6.y]=6; field[Q7.x][Q7.y]=7; field[Q8.x][Q8.y]=8; print(field,8); cout<<"-------------------------------------------------------------------------------\n"; cout<<"-------------------------------------------------------------------------------\n"; cout<<"It was taken "<<z<<" loops to find the combination\n"; cout<<"Are you going to continue (y/n)? "; cin>>stop; } } } int placeQueen(int array1[][8],int x, int y) { bool filled=false; //check if the cell is not fille by another queen if (array1[x][y]==-1) return 0; else { for (int i=y; i<8; i++) if (array1[x][i]==-1) filled=true; for (int i=y; i>=0; i--) if (array1[x][i]==-1) filled=true; for (int i=x; i<8; i++) if (array1[i][y]==-1) filled=true; for (int i=x; i>=0; i--) if (array1[i][y]==-1) filled=true; for (int i=x, j=y; i<8, j<8; i++, j++) if (array1[i][j]==-1) filled=true; for (int i=x, j=y; i>=0, j>=0; i--, j--) if (array1[i][j]==-1) filled=true; for (int i=x, j=y; i<8, j>=0; i++, j--) if (array1[i][j]==-1) filled=true; for (int i=x, j=y; i>=0, j<8; i--, j++) if (array1[i][j]==-1) filled=true; if (filled==false) return 1; else return 0; } } void print(int field[][8], int arraySize) { system("cls"); for (int i=0; i<arraySize; i++) { for (int j=0; j<arraySize; j++) cout<<field[i][j]<<"\t"; cout<<"\n\n\n"<<endl; } } void cleanUp(int field[][8], int arraySize) { for (int i=0; i<arraySize; i++) for (int j=0; j<arraySize; j++) field[i][j]=0; } /* */
评论
    相关推荐