How to implement deep priority traversal (DFS)

Source: Internet
Author: User

The DFS implementation steps are as follows:

① Access vertex v and mark that V has accessed

② Find the first vertex W of V

③ If W exists, the execution continues; otherwise, the algorithm ends.

④ If W is not accessed, use DFS to recursively access W

⑤ Search for the next adjacent node of V, mark it as W, and go to step ③


For DFS, the access order is

A B D C E

The pseudocode is as follows:

Vector <int> G [maxn] int vis [maxn] void DFS (int u) {vis [u] = 1; // set it to int d = G [u]. size () // obtain all the adjacent nodes of vertex u. The number is d For (INT I = 0; I <D; I ++) {int v = G [u] [I]; // scan all adjacent vertices. If no, DFS accesses this vertex if (! Vis [v]) DFS (v );}}


Complete the Code:

# Include <iostream> using namespace STD; # define vertexsize 10int visit [vertexsize]; typedef struct {int weight [vertexsize] [vertexsize];} graph; void initiate_graph (graph * G, int N) {int I, j; for (I = 0; I <n; I ++) visit [I] = 0; For (j = 0; j <N; j ++) {if (I = J) g-> weight [I] [J] = 0; else G-> weight [I] [J] = 0x7fff;} void insertedge (graph * g, int V, int W, int weight, int N) {If (v <0 | V> = n | W <0 | W> = N) {cout <"overflow! "<Endl;} G-> weight [v] [W] = weight;} void DFS (graph * g, int U, int N) {cout <u <"; visit [u] = 1; int I; for (I = 0; I <n; I ++) {If (G-> weight [u] [I]> 0 & G-> weight [u] [I] <0x7fff &&! Visit [I]) {visit [I] = 1; DFS (G, I, n) ;}} void main () {graph G; int N, edge; cout <"Enter the number of vertices in the graph:" <Endl; CIN> N; cout <"Enter the number of edges in the graph" <Endl; cin> edge; initiate_graph (& G, n); int I, P1, P2, weight; cout <"Enter vertex-weight:" <Endl; for (I = 0; I <edge; I ++) {CIN> P1> P2> weight; insertedge (& G, P1, P2, weight, n);} DFS (& G, 0, n); System ("pause ");}


How to implement deep priority traversal (DFS)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.