711152. Alex Travelling

Medium

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:

  1. Create an adjacency list representation of the graph.
  2. Define a recursive function traverse that takes a node as input and returns the number of distinct routes it can take to reach that node.
  3. Initialize a variable count to 0, which will store the total number of distinct routes.
  4. Call the traverse function on the starting point, passing the current count as an argument.
  5. 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

View on GeeksforGeeks
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));
    }
}

DevExCode

Master coding interviews with Leetcode, system design, TechBit, QuickLearn, DevTips, Tech Battles, and career services.

© 2026 DevExCode. All rights reserved.