In your childhood you most likely had to solve the riddle of the house of Santa Claus. Do you remember that the importance was on drawing the house in a stretch without lifting the pencil and not drawing a line twice? As a reminder it has to look like shown in Figure 1.
Figure: The House of Santa Claus
Well, a couple of years later, like now, you have to ``draw'' the house again but on the computer. As one possibility is not enough, we require all the possibilities when starting in the lower left corner. Follow the example in Figure 2 while defining your stretch.
Figure: This Sequence would give the Outputline 153125432
All the possibilities have to be listed in the outputfile by increasing order, meaning that 1234... is listed before 1235... .
So, an outputfile could look like this:
12435123 13245123 ... 15123421
使用递归进行搜索:
#include<iostream> #include <string > #include <cstring > using namespace std; int map[6][6]; //在这里注意第一行时没有用的,全部设置为0 void makemap() { memset(map,0,sizeof(map)); for(int i=1;i<=5;i++) for(int j=1;j<=5;j++) if(i!=j) //标记除了自己外不能访问自己 map[i][j]=1; map[4][1]=map[1][4]=0; //由于2和4 1和4不能直接相连,所以为0 map[4][2]=map[2][4]=0; } void dfs(int x,int k,string s) { s=s+char(x+'0'); //记录路径 if(k==8) //记录路径的长度 { cout<<s<<endl; return ; } for(int y=1;y<=5;y++) if(map[x][y]) { map[x][y]=map[y][x]=0; dfs(y,k+1,s); //递归求出所有路线 map[x][y]=map[y][x]=1;//恢复原形状 } } int main () { makemap(); dfs(1,0,""); //第三个参数为路径字符串 return 0; }