BUPT-homework/semester3/pset7/7-2-DFS.c

75 lines
1.1 KiB
C
Raw Normal View History

2022-11-28 16:32:09 +08:00
#include <stdio.h>
#include <stdlib.h>
#define SIZE 9
typedef struct stack {
int top;
int *arr;
} stack;
stack *newStack() {
stack *st = malloc(sizeof(stack));
st->top = 0;
st->arr = malloc(sizeof(int) * SIZE * 3);
return st;
}
void push(stack *st, int i) { st->arr[st->top++] = i; }
int pop(stack *st) { return st->arr[--st->top]; }
int isEmpty(stack *st) { return (st->top == 0); }
int main(void) {
int mat[SIZE][SIZE] = {};
mat[1][2] = 1;
mat[1][3] = 1;
mat[2][1] = 1;
mat[2][4] = 1;
mat[2][5] = 1;
mat[3][1] = 1;
mat[3][6] = 1;
mat[3][7] = 1;
mat[4][2] = 1;
mat[4][8] = 1;
mat[5][2] = 1;
mat[5][8] = 1;
mat[6][3] = 1;
mat[6][8] = 1;
mat[7][3] = 1;
mat[7][8] = 1;
mat[8][4] = 1;
mat[8][5] = 1;
mat[8][6] = 1;
mat[8][7] = 1;
int visited[SIZE] = {};
int start;
scanf("%d", &start);
stack *st = newStack();
push(st, start);
int cur;
while (!isEmpty(st)) {
cur = pop(st);
if (!visited[cur]) {
visited[cur] = 1;
printf("%d,", cur);
}
for (int i = SIZE - 1; i > 0; i--) {
if (!visited[i] && mat[cur][i] == 1) {
push(st, i);
}
}
}
return 0;
}