用DFS去做
Code #1是正規做法,Code #2是超級做法= =可是為什麼我送出以後發現#2比#1還慢-_-""
Code #1
#include <stdio.h>
#include <stdbool.h>
bool map[6][6] = {false}, used[6][6] = {false};
int ans[8];
void dfs(int depth, int node)
{
int i;
if (depth >= 8)
{
for (i = 0; i < 8; i++)
printf("%d", ans[i]);
printf("%d\n", node);
return;
}
ans[depth] = node;
for (i = 1; i <= 5; i++)
if (map[node][i] && !used[node][i])
{
used[node][i] = used[i][node] = true;
dfs(depth+1, i);
used[node][i] = used[i][node] = false;
}
}
int main(void)
{
map[1][2] = map[2][1] = map[1][3] = map[3][1] = map[1][5] = map[5][1] = true;
map[2][3] = map[3][2] = map[2][5] = map[5][2] = true;
map[3][4] = map[4][3] = map[3][5] = map[5][3] = true;
map[4][5] = map[5][4] = true;
dfs(0, 1);
return 0;
}
Code #2
#include <stdio.h>
int main(void)
{
printf("123153452\n123154352\n123451352\n123453152\n123513452\n123543152\n125134532\n125135432\n125315432\n125345132\n125431532\n125435132\n132153452\n132154352\n132534512\n132543512\n134512352\n134512532\n134521532\n134523512\n134532152\n134532512\n135123452\n135125432\n135215432\n135234512\n135432152\n135432512\n152134532\n152135432\n152345312\n152354312\n153123452\n153125432\n153213452\n153254312\n153452132\n153452312\n154312352\n154312532\n154321352\n154325312\n154352132\n154352312\n");
return 0;
}
沒有留言:
張貼留言