Module: Search in depth. DFS


Problem

1/12

DFS: Beginning (C++)

Theory Click to read/hide

DFS DFS
Depth first search (DFS) is one of the main algorithms on graphs. The algorithm runs in O(N + M).
 
Algorithm
To begin with, we start from the top, consider the children of this top, and if we have never entered them, then we start DFS from them.


Problem

Write a procedure void dfs (int v) that traverses the depth of an undirected graph from the start vertex S and outputs all vertices in traversal order, starting at vertex S separated by a space on one line.

The first line contains three numbers N  - the number of vertices in the graph, M - the number of edges, S - the starting vertex. In the following M lines, 2 variables Ui and Vi are supplied , description of graph edges. All numbers in the input do not exceed 1000.

Output all vertices in order of traversal by DFS.

In the above program, g[i][j] means that there is an edge between the vertices i and j, and in the array used we mark whether we have visited this peak.