全排列(深度优先遍历)

一.代码

#include<stdio.h>
#include<malloc.h>
int n;
int* a;
int* used;
int* path;

void init() {
	printf("请输入n:");
	scanf("%d", &n);
	a = (int*)malloc(sizeof(int) * n);
	used = (int*)malloc(sizeof(int) * n);
	path = (int*)malloc(sizeof(int) * n);
	for (int i = 0; i < n; i++) {
		scanf("%d", a + i);
		used[i] = 0;
	}
}

void dfs(int depth) {
	if (depth == n) {
		for (int i = 0; i < n; i++)
			printf("%d ", path[i]);
		printf("\n");
	}
	for (int i = 0; i < n; i++) {
		if (used[i])
			continue;
		used[i] = 1;
		path[depth] = a[i];
		dfs(depth + 1);
		used[i] = 0;
	}
}

void fullPermutation() {
	printf("所给数的全排列有:\n");
	dfs(0);
}

int main() {
	init();
	fullPermutation();
	return 0;
}

二.递归树

三.总结

学习初级的图的运用。
posted @ 2022-11-17 19:40  彭乐祥  阅读(44)  评论(0编辑  收藏  举报