回溯法:
注意状态的转换,用尽量少的数据记录状态表,注意搜索的方向
例如八皇后问题: 只需记录列数 是否可用;
搜索方向的为:搜索当前行+搜索下一行
#include <iostream> using namespace std; int ROW,COL,total; bool squares [26][26]; int path[26*26][2]; bool find; void printPath(){ for (int i=0;i<total;i++) { cout<<(char)(path[i][0]+’A’)<<path[i][1]+1; } cout<<endl; } void dfs(int preR,int preC,int pos) //find pos { if (find) { return; } //record pre information path[pos-1][0]=preR; path[pos-1][1]=preC; squares[preR][preC]=false; // cout<<“dfs(“<<preR<<“,”<<preC<<“) find: “<<pos<<endl; if (pos==total) { find =true; printPath(); return; } int rs[8]; int cs[8]; rs[0]=preR-2; rs[1]=preR-2; rs[2]=preR-1; rs[3]=preR-1; rs[4]=preR+1; rs[5]=preR+1; rs[6]=preR+2; rs[7]=preR+2; cs[0]=preC-1; cs[1]=preC+1; cs[2]=preC-2; cs[3]=preC+2; cs[4]=preC-2; cs[5]=preC+2; cs[6]=preC-1; cs[7]=preC+1; int r,c; for (int i=0;i<8;i++) { r=rs[i]; c = cs[i]; if ( r<ROW && c<COL && r>=0 && c>=0 && squares[r][c]) { dfs(r,c,pos+1); } } squares[preR][preC]=true; } void solve(){ find=false; for (int i = 0; i < ROW ; i++) { for (int j = 0; j < COL ; j++) { dfs(i,j,1); if (find) { return; } } } if (!find) { cout<<“impossible”<<endl; } } int main() { int caseNum; cin>>caseNum; for (int i = 1; i <= caseNum ; i++) { cin>>COL>>ROW; //col:1 2 3 …COL //ROW:A,B total = COL*ROW; cout<<“Scenario #”<<i<<“:”<<endl; memset(squares,true,sizeof(bool)*26*26); //init value is true,means not visited solve(); cout<<endl; } return 0; }