📌  相关文章
📜  在图中顶点V处终止的最长路径的长度

📅  最后修改于: 2021-04-17 18:54:39             🧑  作者: Mango

给定一个二进制矩阵mat [] [] ,它表示图的邻接矩阵表示,其中mat [i] [j]1表示在顶点ij与顶点V之间存在边,则任务是找到从任何节点到顶点X的最长路径,因此路径中的每个顶点仅出现一次。

例子:

方法:给定的问题可以通过在从为V源节点的给定的图执行DFS遍历和寻找具有从结点V的最深节点的路径的最大长度来解决。
请按照以下步骤解决问题:

  • 从矩阵mat [] []中的给定Graph表示形式初始化一个邻接表,例如Adj []
  • 初始化一个辅助向量,例如visited [],以跟踪是否已访问任何顶点。
  • 初始化一个变量,例如distance0 ,以存储从任何源节点到给定顶点V的结果路径的最大长度。
  • 从节点V对给定图执行DFS遍历,并执行以下步骤:
    • 将当前节点V标记为已访问,即, visited [V] = true
    • 距离值更新为最大距离水平
    • 遍历当前源节点V的邻接表。如果子节点与父节点不同并且尚未访问,则以dfs(child,Adj,Visited,level + 1,distance)递归执行DFS遍历。
    • 完成上述步骤后,如果给定图中存在循环,则将当前节点V标记为未访问,以包括路径。
  • 完成上述步骤后,将distance的值打印为任何源节点与给定节点V之间的结果最大距离。

下面是上述方法的实现:

C++
// C++ program for the above approach
#include 
using namespace std;
 
// Function to perform DFS Traversal from
// source node to the deepest node and
// update maximum distance to the deepest node
void dfs(int src, vector Adj[],
         vector& visited, int level,
         int& distance)
{
 
    // Mark source as visited
    visited[src] = true;
 
    // Update the maximum distance
    distance = max(distance, level);
 
    // Traverse the adjacency list
    // of the current source node
    for (auto& child : Adj[src]) {
 
        // Recursively call
        // for the child node
        if (child != src
            and visited[child] == false) {
            dfs(child, Adj, visited,
                level + 1, distance);
        }
    }
 
    // Backtracking step
    visited[src] = false;
}
 
// Function to calculate maximum length
// of the path ending at vertex V from
// any source node
int maximumLength(vector >& mat,
                  int V)
{
 
    // Stores the maximum length of
    // the path ending at vertex V
    int distance = 0;
 
    // Stores the size of the matrix
    int N = (int)mat.size();
 
    // Stores the adjacency list
    // of the given graph
    vector Adj[N];
 
    vector visited(N, false);
 
    // Traverse the matrix to
    // create adjacency list
    for (int i = 0; i < N; i++) {
        for (int j = 0; j < N; j++) {
            if (mat[i][j] == 1) {
                Adj[i].push_back(j);
            }
        }
    }
 
    // Perform DFS Traversal to
    // update the maximum distance
    dfs(V, Adj, visited, 0, distance);
 
    return distance;
}
 
// Driver Code
int main()
{
    vector > mat = { { 0, 1, 0, 0 },
                                 { 1, 0, 1, 1 },
                                 { 0, 1, 0, 0 },
                                 { 0, 1, 0, 0 } };
    int V = 2;
 
    cout << maximumLength(mat, V);
 
    return 0;
}


Java
// Java program for the above approach
import java.util.ArrayList;
 
class GFG{
     
static int distance;
 
// Function to perform DFS Traversal from source node to
// the deepest node and update maximum distance to the
// deepest node
private static void dfs(int src, ArrayList> Adj,
                                 ArrayList visited, int level)
{
     
    // Mark source as visited
    visited.set(src, true);
 
    // Update the maximum distance
    distance = Math.max(distance, level);
 
    // Traverase the adjacency list of the current
    // source node
    for(int child : Adj.get(src))
    {
         
        // Recursively call for the child node
        if ((child != src) &&
            (visited.get(child) == false))
        {
            dfs(child, Adj, visited, level + 1);
        }
    }
     
    // Backtracking step
    visited.set(src, false);
}
 
// Function to calculate maximum length of the path
// ending at vertex v from any source node
private static int maximumLength(int[][] mat, int v)
{
     
    // Stores the maximum length of the path ending at
    // vertex v
    distance = 0;
 
    // Stores the size of the matrix
    int N = mat[0].length;
 
    ArrayList visited = new ArrayList();
 
    for(int i = 0; i < N; i++)
    {
        visited.add(false);
    }
 
    // Stores the adjacency list of the given graph
    ArrayList<
    ArrayList> Adj = new ArrayList<
                                  ArrayList>(N);
 
    for(int i = 0; i < N; i++)
    {
        Adj.add(new ArrayList());
    }
 
    int i, j;
 
    // Traverse the matrix to create adjacency list
    for(i = 0; i < mat[0].length; i++)
    {
        for(j = 0; j < mat.length; j++)
        {
            if (mat[i][j] == 1)
            {
                Adj.get(i).add(j);
            }
        }
    }
     
    // Perform DFS Traversal to update
    // the maximum distance
    dfs(v, Adj, visited, 0);
    return distance;
}
 
// Driver code
public static void main(String[] args)
{
    int[][] mat = { { 0, 1, 0, 0 },
                    { 1, 0, 1, 1 },
                    { 0, 1, 0, 0 },
                    { 0, 1, 0, 0 } };
    int v = 2;
     
    System.out.print(maximumLength(mat, v));
}
}
 
// This code is contributed by abhinavjain194


Python3
# Python3 program for the above approach
visited = [False for i in range(4)]
 
# Function to perform DFS Traversal from
# source node to the deepest node and
# update maximum distance to the deepest node
def dfs(src, Adj, level, distance):
     
    global visited
     
    # Mark source as visited
    visited[src] = True
 
    # Update the maximum distance
    distance = max(distance, level)
 
    # Traverse the adjacency list
    # of the current source node
    for child in Adj[src]:
         
        # Recursively call
        # for the child node
        if (child != src and visited[child] == False):
            dfs(child, Adj, level + 1, distance)
 
    # Backtracking step
    visited[src] = False
 
# Function to calculate maximum length
# of the path ending at vertex V from
# any source node
def maximumLength(mat, V):
     
    # Stores the maximum length of
    # the path ending at vertex V
    distance = 0
 
    # Stores the size of the matrix
    N = len(mat)
 
    # Stores the adjacency list
    # of the given graph
    Adj = [[] for i in range(N)]
 
    # Traverse the matrix to
    # create adjacency list
    for i in range(N):
        for j in range(N):
            if (mat[i][j] == 1):
                Adj[i].append(j)
 
    # Perform DFS Traversal to
    # update the maximum distance
    dfs(V, Adj, 0, distance)
 
    return distance + 2
 
# Driver Code
if __name__ == '__main__':
     
    mat = [ [ 0, 1, 0, 0 ],
            [ 1, 0, 1, 1 ],
            [ 0, 1, 0, 0 ],
            [ 0, 1, 0, 0 ] ]
 
    V = 2
     
    print(maximumLength(mat, V))
 
# This code is contributed by ipg2016107


输出:
2

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