|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
学校的一道题
其中dfs函数里用红字部分的是要自己填上去的,一共五个空,想不通为什么最后一句还要往visited数组里写true。
并且第四行和第五行的遍历为什么会错了
#include<stdio.h>
#include<stdbool.h>
#define N 7
const int a[N][N] = {
{0,1,1,0,0,0,0},
{1,0,1,1,0,0,0},
{1,1,0,0,1,0,0},
{0,1,0,0,1,1,0},
{0,0,1,1,0,0,1},
{0,0,0,1,0,0,0},
{0,0,0,0,1,0,0},
};
int count=0;
void print_path(int n, int path[]) {
for (int i = 0; i < n; i++)
printf("%d", path[i]);
printf("\n");
}
void dfs(int step, int goal, int path[], bool visited[]) {
count++;
int x = path[step - 1];
if (x == goal) {
print_path(step, path);
}
else
{
for (int i = 0; i < N; i++) {
if (a[x][i] == 0)
continue;
if (!visited[i]) {
path[i] = i;
visited[i] = true;
dfs(i+1, goal, path, visited);
visited[i] = true;
}
}
}
}
void traverse(int start, int goal) {
int path[N];
bool visited[N];
for (int i = 0; i < N; i++)
visited[i] = false;
path[0] = start;
visited[start] = true;
dfs(1, goal, path, visited);
}
int main(void) {
traverse(0, 6);
printf("%d", count);
return 0;
}
|
|