深度优先搜索算法(Depth First Search)

无向图的DFS

方法一:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
#include <iostream>
using namespace std;
const int MAX=100;
bool visited[MAX]={false};
int adj[MAX][MAX]={0};

int n,m;  //n is the number of nodes, m is the number of edges

void dfs(int u){
    visited[u]=true;
    cout<<u<<" ";

    for (int v = 0; v < n; v++){
        if(adj[u][v] && !visited[v])
        dfs(v);
    }
}

int main(){
    cin >>n>>m;
    for (int  i = 0; i <m; i++){
        int u,v;
        cin>>u>>v;
        adj[u][v]=adj[v][u]=1;
    }
    dfs(0);  //start DFS from node 0
    return 0;
}

方法二:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
#include <iostream>
#include <stack>
using namespace std;

const int MAXN = 100; // Maximum number of vertices in the graph

int adjMat[MAXN][MAXN]; // Adjacency matrix representing the graph
bool visited[MAXN]; // Array to keep track of visited vertices
  int n, m; // n = number of vertices, m = number of edges

void dfs(int start) {
    stack<int> st; // Stack to keep track of visited vertices
    st.push(start); // Push the starting vertex onto the stack

    while (!st.empty()) {
        int cur = st.top(); // Get the top vertex on the stack
        st.pop(); // Pop the top vertex from the stack

        if (!visited[cur]) {
            visited[cur] = true; // Mark the vertex as visited
            cout << cur << " "; // Print the vertex

            // Add the unvisited neighbors of the current vertex to the stack
            for (int i = 0; i < n; i++) {
                if (adjMat[cur][i] && !visited[i]) {
                    st.push(i);
                }
            }
        }
    }
}

int main() {
  
    cin >> n >> m;

    // Initialize the adjacency matrix to all zeros
    for (int i = 0; i < n; i++) {
        for (int j = 0; j < n; j++) {
            adjMat[i][j] = 0;
        }
    }

    // Read in the edges of the graph and update the adjacency matrix
    for (int i = 0; i < m; i++) {
        int u, v; // u and v are the endpoints of an edge
        cin >> u >> v;
        adjMat[u][v] = 1;
        adjMat[v][u] = 1; // If the graph is undirected
    }

    // Perform a depth-first search starting from vertex 0
    dfs(0);

    return 0;
}

Scroll to Top