Description
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> #include <cstdio> using namespace std; int map[10][10]; void again_map()//生成无向图的相邻矩阵 { memset(map,0,sizeof(map)); int i,j; for(i=1;i<=5;i++) for(j=1;j<=5;j++) if(i!=j) map[i][j]=1; //因为2和4之间1和4之间是不可以直接相连的所以标记为不能再访问 map[2][4]=0; map[4][2]=0; map[1][4]=0; map[4][1]=0; } void dfs(int n,int ans,string s) { s+=char(n+'0');//记录经过的路径 if(ans==8)//如果完成了一笔画则输出路径 { cout<<s<<endl; return ; } int m; for(m=1;m<=5;m++)//从小到大遍历未走过的路径 if(map[n][m]) { map[n][m]=map[m][n]=0;//标记访问过的变数 dfs(m,ans+1,s);//递归下一条路径,走过的边数加一 map[n][m]=map[m][n]=1;//恢复改边的未访问标记 } } int main() { again_map(); dfs(1,0,"");//从节点一出发计算所有可能的访问序列 return 0; }代码二:
#include <iostream> #include <cstring> #include <cstdio> using namespace std; int map[6][6]; int path[10]; void again_map() { 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[2][4]=map[4][2]=0; map[1][4]=map[4][1]=0; } void dfs(int n,int k) { path[k]=n; if(k==8) { for(int i=0;i<=8;i++) printf("%d",path[i]); printf("\n"); return ; } int m; for(m=1;m<=5;m++) { if(map[n][m]) { map[n][m]=map[m][n]=0; dfs(m,k+1); map[n][m]=map[m][n]=1; } } } int main() { again_map(); dfs(1,0); return 0; }