#include <cstdlib> #include <iostream> using namespace std; class card{ private: int a[5][5];//原题 int b[5][5];//解决方案 int c[5][5];//桥 int s[5][5];//结果串 int counts;//解数目 public: card (char x[25]); void Backtrack (int t); bool Constraint(int t); bool Bound (int t); bool Solution(); void Output(); void turn(int i,int j); void IfnoSolution(); }; int main(int argc, char *argv[]) { char s[25]; cout<<"请输入5X5的零一矩阵"<<endl; for(int i=0;i<5;i++){ for(int j=0;j<5;j++){ s[i*5+j]=getchar(); } getchar(); } card cd(s); cd.Backtrack(1); cd.IfnoSolution(); system("PAUSE"); return EXIT_SUCCESS; } void card::Backtrack(int t){ if (t > 25 ){//到达叶节点 Output(); } else{ for (int i = 0;i<=1;i++){ b[t/5][t%5-1] = i; Backtrack(t+1); } } } card::card(char x[25]){ cout<<"题目:"<<endl; for(int i=0;i<5;i++){ for(int j=0;j<5;j++){ a[i][j]=x[i*5+j]-48; cout<<a[i][j]; } cout<<endl; } counts=0; cout<<endl; } bool card::Constraint (int t){ ; } bool card::Bound (int t){ ; } bool card::Solution(){ for(int i=0;i<5;i++){ for(int j=0;j<5;j++){ c[i][j]=a[i][j]; } } for(int i=0;i<5;i++){ for(int j=0;j<5;j++){ if(b[i][j]==1){ turn(i,j); } } } for(int i=0;i<5;i++){ for(int j=0;j<5;j++){ if(c[i][j]==1){ return false;//只要有一个就错 } } } counts++; return true; } void card::Output(){ if(Solution()){ cout<<"解"<<counts<<":"<<endl; for(int i=0;i<5;i++){ for(int j=0;j<5;j++){ s[i][j]=b[i][j]; cout<<s[i][j]; } cout<<endl; } cout<<endl; } } void card::IfnoSolution(){ if(counts==0)cout<<"无解!"<<endl; } void card::turn(int i,int j){ if(c[i][j]==0) c[i][j]=1; else c[i][j]=0; if(i>0){ if(c[i-1][j]==0) c[i-1][j]=1; else c[i-1][j]=0; } if(i<4){ if(c[i+1][j]==0) c[i+1][j]=1; else c[i+1][j]=0; } if(j>0){ if(c[i][j-1]==0) c[i][j-1]=1; else c[i][j-1]=0; } if(j<4){ if(c[i][j+1]==0) c[i][j+1]=1; else c[i][j+1]=0; } }
时间: 2024-11-08 21:42:21