给定一个表示图的邻接矩阵表示的二元矩阵mat[][] ,其中mat[i][j]为1表示顶点i和j与顶点V之间存在边,任务是找到从任何节点到顶点X的最长路径,使得路径中的每个顶点只出现一次。
例子:
Input: graph[][] = {{0, 1, 0, 0}, {1, 0, 1, 1}, {0, 1, 0, 0}, {0, 1, 0, 0}}, V = 2
Output: 2
Explanation:
The given graph is as follows:
0
|
1
/ \
2 3
The longest path ending at vertex 2 is 3 -> 1 -> 2. Therefore, the length of this path is 2.
Input: graph[][] = {{0, 1, 1, 1}, {1, 0, 0, 0}, {1, 0, 0, 0}, {1, 0, 0, 0}}, V = 1
Output: 2
方法:给定的问题可以通过对从源节点作为V的给定图执行 DFS 遍历并找到从节点V 开始具有最深节点的路径的最大长度来解决。
请按照以下步骤解决问题:
- 从矩阵mat[][] 中的给定 Graph 表示初始化一个邻接表,比如Adj [] 。
- 初始化一个辅助向量,比如visited[],以跟踪是否有任何顶点被访问。
- 初始化一个变量,比如distance为0 ,以存储从任何源节点到给定顶点V的结果路径的最大长度。
- 对来自节点V的给定图执行 DFS 遍历并执行以下步骤:
- 将当前节点V标记为已访问,即visited[V] = true 。
- 将distance的值更新为distance和level的最大值。
- 遍历当前源节点V的邻接表。如果子节点与父节点不同且尚未访问,则递归执行 DFS Traversal 作为dfs(child, Adj,visited, level + 1, distance) 。
- 完成上述步骤后,如果给定图中存在循环,则将当前节点V标记为未访问以包含路径。
- 完成上述步骤后,打印距离值作为任何源节点与给定节点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
C#
// C# program for the above approach
using System;
using System.Collections;
using System.Collections.Generic;
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
static void dfs(int src, List> Adj,
List visited, int level)
{
// Mark source as visited
visited[src] = true;
// Update the maximum distance
distance = Math.Max(distance, level);
// Traverase the adjacency list of
// the current source node
foreach(int child in Adj[src])
{
// Recursively call for the child node
if ((child != src) &&
(visited[child] == false))
{
dfs(child, Adj, visited, level + 1);
}
}
// Backtracking step
visited[src] = false;
}
// Function to calculate maximum length of the path
// ending at vertex v from any source node
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.GetLength(0);
List visited = new List();
for(int i = 0; i < N; i++)
{
visited.Add(false);
}
// Stores the adjacency list of the given graph
List> Adj = new List>(N);
for(int i = 0; i < N; i++)
{
Adj.Add(new List());
}
// Traverse the matrix to create adjacency list
for(int i = 0; i < mat.GetLength(0); i++)
{
for(int j = 0; j < mat.GetLength(0); j++)
{
if (mat[i, j] == 1)
{
Adj[i].Add(j);
}
}
}
// Perform DFS Traversal to update
// the maximum distance
dfs(v, Adj, visited, 0);
return distance;
}
// Driver code
static void Main()
{
int[,] mat = { { 0, 1, 0, 0 },
{ 1, 0, 1, 1 },
{ 0, 1, 0, 0 },
{ 0, 1, 0, 0 } };
int v = 2;
Console.Write(maximumLength(mat, v));
}
}
// This code is contributed by mukesh07
Javascript
输出:
2
时间复杂度: O(N 2 )
辅助空间: O(N)
如果您希望与专家一起参加现场课程,请参阅DSA 现场工作专业课程和学生竞争性编程现场课程。