深度优先遍历DFS
2016-12-17 10:24
369 查看
//邻接数组表示法 #include<iostream> #include<cstdlib> #define MAX 5 #define QueueNum 10 using namespace std; struct Node { int vertex; struct Node* next; }; typedef struct Node* Graph; Node Head[MAX]; int flag = 0; //0为无向图 1为有向图 int visited[MAX] = { 0 };//标记是否访问过 void DFS(int vertex) { Graph pointer=Head[vertex].next; cout<<vertex<<"->"; visited[vertex]=1; while(pointer!=NULL) { if(visited[pointer->vertex]==0) DFS(pointer->vertex); pointer=pointer->next; } } void init() { int i; for (i = 0; i<MAX; i++) { Head[i].vertex = i; Head[i].next = NULL; } } void printGraph() { Graph pointer; int i; for (i = 0; i<MAX; i++) { pointer = &(Head[i]); cout << '[' << i << ']'; while (pointer->next != NULL) { pointer = pointer->next; cout << "->[" << pointer->vertex << ']'; } cout << endl; } } void GreatGraph(int start, int end) { Graph New = (Graph)malloc(sizeof(struct Node)); Graph pointer; if (New != NULL) { New->vertex = end; New->next = NULL; pointer = &(Head[start]); while (pointer->next != NULL) pointer = pointer->next; pointer->next = New; if (flag == 0) { New = (Graph)malloc(sizeof(struct Node)); New->vertex = start; New->next = NULL; pointer = &(Head[end]); while (pointer->next != NULL) pointer = pointer->next; pointer->next = New; } } } int main(void) { int start, end, n, i,begin; init(); cout << "请输入(0:无向图 1:有向图):"; cin >> flag; cout << "请输入要添加的边数:"; cin >> n; for (i = 1; i <= n; i++) { cin >> start >> end; GreatGraph(start, end); } cout<<"请输入开始遍历的结点:"; cin>>begin; DFS(begin); // printGraph(); return 0; }
相关文章推荐
- leetcode 690. Employee Importance 员工重要性求和 + 深度优先遍历DFS
- 第十二周项目3--图遍历算法实现--实现深度优先遍历--DFS
- leetcode 144. Binary Tree Preorder Traversal 二叉树前序遍历 + 深度优先遍历DFS
- 深度优先遍历 DFS C实现
- 【算法——02】图的遍历——BFS广度优先搜索、DFS深度优先搜索
- 图——图的遍历——深度优先遍历DFS
- leetcode 617. Merge Two Binary Trees 二叉树合并 + 深度优先遍历DFS
- Java 图的建立及DFS深度优先遍历
- 题目1461:Tempter of the bone(深度优先遍历DFS)
- leetcode 97. Interleaving String(字符串交错出现) DFS深度优先遍历 + 很明显很经典的DP动态规划做法
- leetcode 139. Word Break 深度优先遍历DFS按照index递归搜索 + 很棒的动态规划DP做法
- zoj 2100(dfs深度优先遍历)
- leetcode 235. Lowest Common Ancestor of a Binary Search Tree 二叉搜索树BST的最近公共祖先LCA + 深度优先遍历DFS
- leetcode 394. Decode String 字符串解码 + DFS深度优先遍历求解
- leetcode 399. Evaluate Division 等式求解+典型的DFS深度优先遍历
- DFS-深度优先遍历
- leetcode 377. Combination Sum IV 组合之和 + DP动态规划 + DFS深度优先遍历
- python遍历文件夹——深度优先(DFS)/广度优先(BFS)
- leetcode 530. Minimum Absolute Difference in 二叉搜索树的中序遍历 + 深度优先遍历DFS
- leetcode 749. Contain Virus 消灭病毒建立墙 + 深度优先遍历DFS