数据结构—邻接表的DFS
原理:参考趣学数据结构
代码:
# include <stdio.h>
# include <stdlib.h>
# define typeNode int
# define N 100
int degree[ N] ;
int result[ N] ;
bool visited[ N] ;
typedef struct dNode { int data; struct dNode * next;
} dNode;
typedef struct mNode { typeNode data; dNode * first;
} mNode;
typedef struct { mNode vNode[ N] ; int vNum, eNum;
} zNode;
void init ( zNode & ZNode) { printf ( "规定顶点从0开始取\n" ) ; scanf_s ( "%d%d" , & ZNode. vNum, & ZNode. eNum) ; for ( int i = 0 ; i < ZNode. vNum; i++ ) { scanf_s ( "%d" , & ZNode. vNode[ i] . data) ; ZNode. vNode[ i] . first = NULL ; } for ( int i = 0 ; i < ZNode. eNum; i++ ) { int u, v; scanf_s ( "%d%d" , & u, & v) ; dNode* p = new dNode ( ) ; p-> data = v; p-> next = ZNode. vNode[ u] . first; ZNode. vNode[ u] . first= p; }
}
void print12 ( zNode ZNode) { printf ( "遍历链表:\n" ) ; for ( int i = 0 ; i < ZNode. vNum; i++ ) { dNode* temp = ZNode. vNode[ i] . first; printf ( "%d ->" , ZNode. vNode[ i] . data) ; while ( temp) { printf ( "%d ->" , temp-> data) ; temp = temp-> next; } printf ( "NULL\n" ) ; }
}
void DFSLinkGraph ( zNode ZNode, int u) { visited[ u] = true; printf ( "%d " , u) ; dNode* p = ZNode. vNode[ u] . first; while ( p) { int v = p-> data; if ( ! visited[ v] ) { DFSLinkGraph ( ZNode, v) ; } p = p-> next; }
}
int main ( ) { zNode ZNode; printf ( "邻接表的构造:\n" ) ; init ( ZNode) ; print12 ( ZNode) ; for ( int i = 0 ; i < ZNode. vNum; i++ ) { visited[ i] = false; } printf ( "DFS遍历邻接表\n" ) ; DFSLinkGraph ( ZNode, 0 ) ; printf ( "\n" ) ; system ( "pause" ) ; return 0 ;
}
测试截图:
时间复杂度O(n +e),空间复杂度O(n)
如果存在什么问题,欢迎批评指正!谢谢!