首页 > 其他分享 >深度优先遍历查找

深度优先遍历查找

时间:2022-11-22 22:22:40浏览次数:41  
标签:count 优先 遍历 int depth 查找 key printf path

一.题目

二.思路

深度优先遍历+回溯法

三.代码

#include<stdio.h>
#include<malloc.h>
int n, m;
int* path;
int count[2];//0代表-,1代表o
int key;//第k个
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[i])
            continue;
        count[i]--;
        path[depth] = i;
        search(depth + 1); 
        count[i]++;
    }
}

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

四.总结

全排列的变种题。

图的基本运用。

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

标签:count,优先,遍历,int,depth,查找,key,printf,path
From: https://www.cnblogs.com/cony1/p/16916710.html

相关文章