c语言DFS求 数组中包含的非空子集

107 阅读3分钟
#include <stdio.h>
// 栈
typedef struct Node {
    // 是否已访问
    int visited;
    // 值
    int value;
} Node;
Node NullValue;
typedef struct stack{
    int length;
    Node arrs[10];
}s1;
s1 stack;
Node node[10];
int arrs[10] = { 0,1,2,3,4,5,6,7,8,9 };
int getLength() {
    return stack.length;
}
int getHead() {
    return stack.arrs[stack.length].value;
}
int push(Node a) {
    stack.arrs[stack.length++] = a;
}
void pop() {
    stack.arrs[stack.length--] = NullValue;
}
void display() {
    for (int i = 0; i < stack.length; i++) {
        printf("%d ", stack.arrs[i].value);
    }
    printf("\n");
}
 
int main() {
    int length;
    int j = 0;
    int index,now;
    int i;
    NullValue.value = -1;
    stack.length = 0;
    // 把数组当作 树
    //        0
    //     1    2
    //    3 4  5 6
    //  7 8 9
    for (i = 0; i < 10; i++) {
        node[i].value = arrs[i];
        node[i].visited = 0;
    }
    for (i = 0; i < 10; i++) {
        // 结果
        length = getLength();
        for (j = 0; j <length; j++) {
            pop();
        }
        index = i;
        now = i;
        push(node[i]);
        node[i].visited = 1;
        display();
        index++;
        while (getLength() != 10 - i) {
            if (index < 10) {
                if (node[index].visited == 0) {
                    push(node[index]);
                    node[index].visited = 1;
                    display();
                    pop();
                    index++;
                }
            }
            else {
                index = ++now;
                push(node[index]);
                index++;
                for (j = 0; j < 10; j++) {
                    node[j].visited = 0;
                }
            }
        }
    }
    
    return 0;
}
0
0 1
0 2
0 3
0 4
0 5
0 6
0 7
0 8
0 9
0 1 2
0 1 3
0 1 4
0 1 5
0 1 6
0 1 7
0 1 8
0 1 9
0 1 2 3
0 1 2 4
0 1 2 5
0 1 2 6
0 1 2 7
0 1 2 8
0 1 2 9
0 1 2 3 4
0 1 2 3 5
0 1 2 3 6
0 1 2 3 7
0 1 2 3 8
0 1 2 3 9
0 1 2 3 4 5
0 1 2 3 4 6
0 1 2 3 4 7
0 1 2 3 4 8
0 1 2 3 4 9
0 1 2 3 4 5 6
0 1 2 3 4 5 7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