先根次序周游的非递归算法c程序
#include<stdio.h>
#include<stdlib.h>
#define MAX_SIZE 10
// Data structure for stack
struct Stack{
int data[MAX_SIZE];
int top;
};
// Utility function to initialize stack
void initStack(struct Stack *st) { st->top = -1; }
// Utility function to add an element x in the stack st void push(struct Stack *st,int x) { if(st->top == MAX_SIZE -1) { printf("Stack overflow
"); return; } st->top++; st->data[st->top] = x; }
// Utility function to pop top element from the stack and return it int pop(struct Stack *st) { if(st->top == -1) { printf("Stack underflow
"); return 0; } int x = st->data[st->top]; st->top--; return x; }
// Function to implement depth first search algorithm using non-recursive method void dfsUsingStack(int adjacencyMatrix[][MAX_SIZE],int startVertex,int totalVertex){ struct Stack s; initStack(&s); push(&s,startVertex); int visited[MAX_SIZE] = {0}; visited[startVertex] = 1; while (!isEmpty(&s)){ int currentVertex = pop(&s); printf("%d ",currentVertex); for (int i=0 ; i<totalVertex ; i++){ if (adjacencyMatrix[currentVertex][i]==1 && !visited[i]){ push(&s,i); visited[i]=1; } } } }
// Driver code int main(){ int adjacencyMatrix [MAX_SIZE][MAX_SIZE] ; dfsUsingStack(adjacencyMatrix, 0 , MAX_SIZE ); return 0;}
免责声明:
以上内容除特别注明外均来源于网友提问,创作工场回答,未经许可,严谨转载。