711152. Alex Travelling
Alex Travelling
Slug: alex-travelling
Difficulty: Medium
Id: 711152
Topic Tags: Graph, Data Structures
Company Tags: None
Summary
Alex is planning a trip and wants to know how many different routes she can take from her starting point to her destination. She is given a graph that represents the road network, where each node in the graph corresponds to a junction or an intersection, and the edges represent the roads connecting these nodes. The problem is to write a program that calculates the number of distinct routes Alex can take.
Detailed Explanation
The algorithm for this problem involves using Depth-First Search (DFS) to traverse the graph and keep track of the visited nodes. We start at the starting point, visit all its unvisited neighbors, mark them as visited, and recursively visit their unvisited neighbors until we have visited all reachable nodes from the starting point.
Here's a step-by-step breakdown of the solution:
- Create an adjacency list representation of the graph.
- Define a recursive function
traversethat takes a node as input and returns the number of distinct routes it can take to reach that node. - Initialize a variable
countto 0, which will store the total number of distinct routes. - Call the
traversefunction on the starting point, passing the current count as an argument. - Return the final value of
count.
Time complexity: O(V + E), where V is the number of nodes and E is the number of edges in the graph.
Space complexity: O(V), as we need to store the visited nodes.
Optimized Solutions
Java
import java.util.*;
public class AlexTravelling {
public static int calculateRoutes(int[][] graph, int start, int end) {
boolean[] visited = new boolean[graph.length];
return traverse(graph, start, end, visited, 0);
}
private static int traverse(int[][] graph, int node, int end, boolean[] visited, int count) {
if (node == end) {
return count + 1;
}
visited[node] = true;
for (int neighbor : graph[node]) {
if (!visited[neighbor]) {
count = traverse(graph, neighbor, end, visited, count);
}
}
return count;
}
public static void main(String[] args) {
int[][] graph = {{1, 2}, {0, 3}, {0, 4}, {1, 3}};
System.out.println(calculateRoutes(graph, 0, 3));
}
}