深度优先遍历查找

一.题目

二.思路

深度优先遍历+回溯法

三.代码

#include<stdio.h>
#include<malloc.h>
int n, m;
int* path;
int count[2];//0代表-,1代表o
int key;//第k个
long long int count_ = 0;

void init() {
    printf("请输入n,m,k:");
    scanf("%d %d %d", &n, &m, &key);
    path = (int*)malloc(sizeof(int) * (n + m));
    count[0] = n;
    count[1] = m;
}

void search(int depth) {
    if (depth == n + m) {
        count_++;
        if (count_ == key) {
            for (int i = 0; i < n + m; i++) {
                if (path[i] == 0)
                    printf("-");
                else
                    printf("o");
            }
            printf("\n");
        }
        return;
    }
    for (int i = 0; i < 2; i++) {
        if (count_ == key)
            return;
        if (!count[i])
            continue;
        count[i]--;
        path[depth] = i;
        search(depth + 1);
        count[i]++;
    }
}

int main() {
    init();
    search(0);
    free(path);
    return 0;
}

四.总结

1.全排列的变种题。

2.图的基本运用。

3.目前我还没有更好的做法。

4.递归图

posted @ 2022-11-22 22:19  彭乐祥  阅读(12)  评论(0编辑  收藏  举报