📜  使用 DFS 按节点的字典顺序遍历图

📅  最后修改于: 2021-10-25 03:07:58             🧑  作者: Mango

给定一个图GN 个节点组成,一个源S和一个类型为{u, v}的数组Edges[][2]表示节点uv之间存在无向边,任务是遍历使用 DFS 按字典顺序绘制图形。

例子:

处理方法:按照以下步骤解决问题:

  • 初始化一个映射,比如G以根据节点的字典顺序存储一个节点的所有相邻节点。
  • 初始化一个地图,比如vis检查一个节点是否已经被遍历。
  • 遍历 Edges[][2] 数组,并将图的每个节点的所有相邻节点存储在G 中
  • 最后,使用 DFS 遍历图形并打印图形的访问节点。

下面是上述方法的实现:

C++
// C++ program  for the above approach
#include 
using namespace std;
 
// Function to traverse the graph in
// lexicographical order using DFS
void LexiDFS(map >& G,
             char S, map& vis)
{
    // Mark S as visited nodes
    vis[S] = true;
 
    // Print value of visited nodes
    cout << S << " ";
 
    // Traverse all adjacent nodes of S
    for (auto i = G[S].begin();
         i != G[S].end(); i++) {
 
        // If i is not visited
        if (!vis[*i]) {
 
            // Traverse all the nodes
            // which is connected to i
            LexiDFS(G, *i, vis);
        }
    }
}
 
// Utility Function to traverse graph
// in lexicographical order of nodes
void CreateGraph(int N, int M, int S,
                 char Edges[][2])
{
    // Store all the adjacent nodes
    // of each node of a graph
    map > G;
 
    // Traverse Edges[][2] array
    for (int i = 0; i < M; i++) {
 
        // Add the edges
        G[Edges[i][0]].insert(
            Edges[i][1]);
    }
 
    // Check if a node is already
    // visited or not
    map vis;
 
    // Function Call
    LexiDFS(G, S, vis);
}
 
// Driver Code
int main()
{
    int N = 10, M = 10, S = 'a';
    char Edges[M][2]
        = { { 'a', 'y' }, { 'a', 'z' },
            { 'a', 'p' }, { 'p', 'c' },
            { 'p', 'b' }, { 'y', 'm' },
            { 'y', 'l' }, { 'z', 'h' },
            { 'z', 'g' }, { 'z', 'i' } };
 
    // Function Call
    CreateGraph(N, M, S, Edges);
 
    return 0;
}


Java
// Java program for above approach
import java.util.*;
 
class Graph{
 
// Function to traverse the graph in
// lexicographical order using DFS
static void LexiDFS(HashMap> G,
            char S, HashMap vis)
{
     
    // Mark S as visited nodes
    vis.put(S, true);
 
    // Print value of visited nodes
    System.out.print(S + " ");
 
    // Traverse all adjacent nodes of S
    if (G.containsKey(S))
    {
        for(char i : G.get(S))
        {
             
            // If i is not visited
            if (!vis.containsKey(i) || !vis.get(i))
            {
                 
                // Traverse all the nodes
                // which is connected to i
                LexiDFS(G, i, vis);
            }
        }
    }
}
 
// Utility Function to traverse graph
// in lexicographical order of nodes
static void CreateGraph(int N, int M, char S,
                        char[][] Edges)
{
     
    // Store all the adjacent nodes
    // of each node of a graph
    HashMap> G = new HashMap<>();
 
    // Traverse Edges[][2] array
    for(int i = 0; i < M; i++)
    {
        if (G.containsKey(Edges[i][0]))
        {
            Set temp = G.get(Edges[i][0]);
            temp.add(Edges[i][1]);
            G.put(Edges[i][0], temp);
        }
        else
        {
            Set temp = new HashSet<>();
            temp.add(Edges[i][1]);
            G.put(Edges[i][0], temp);
        }
    }
     
    // Check if a node is already visited or not
    HashMap vis = new HashMap<>();
 
    LexiDFS(G, S, vis);
}
 
// Driver code
public static void main(String[] args)
{
    int N = 10, M = 10;
    char S = 'a';
 
    char[][] Edges = { { 'a', 'y' }, { 'a', 'z' },
                       { 'a', 'p' }, { 'p', 'c' },
                       { 'p', 'b' }, { 'y', 'm' },
                       { 'y', 'l' }, { 'z', 'h' },
                       { 'z', 'g' }, { 'z', 'i' } };
 
    // Function Call
    CreateGraph(N, M, S, Edges);
}
}
 
// This code is contributed by hritikrommie


Python3
# Python3 program  for the above approach
G = [[] for i in range(300)]
vis = [0 for i in range(300)]
 
# Function to traverse the graph in
# lexicographical order using DFS
def LexiDFS(S):
    global G, vis
     
    # Mark S as visited nodes
    vis[ord(S)] = 1
 
    # Prvalue of visited nodes
    print (S,end=" ")
 
    # Traverse all adjacent nodes of S
    for i in G[ord(S)]:
        # If i is not visited
        if (not vis[i]):
            # Traverse all the nodes
            # which is connected to i
            LexiDFS(chr(i))
 
# Utility Function to traverse graph
# in lexicographical order of nodes
def CreateGraph(N, M, S, Edges):
    global G
    # Store all the adjacent nodes
    # of each node of a graph
 
    # Traverse Edges[][2] array
    for i in Edges:
        # Add the edges
        G[ord(i[0])].append(ord(i[1]))
        G[ord(i[0])] = sorted(G[ord(i[0])])
 
    # Function Call
    LexiDFS(S)
 
# Driver Code
if __name__ == '__main__':
    N = 10
    M = 10
    S = 'a'
    Edges=[ ['a', 'y' ],[ 'a', 'z' ],
           [ 'a', 'p' ],[ 'p', 'c' ],
           [ 'p', 'b' ],[ 'y', 'm' ],
           [ 'y', 'l' ],[ 'z', 'h' ],
           [ 'z', 'g' ],[ 'z', 'i' ] ]
 
    # Function Call
    CreateGraph(N, M, S, Edges);
 
# This code is contributed by mohitkumar29.


Javascript


输出:
a p b c y l m z g h i

时间复杂度: O(N * log(N))
辅助空间: O(N)

如果您希望与专家一起参加现场课程,请参阅DSA 现场工作专业课程学生竞争性编程现场课程