Similar Problems

Similar Problems not available

Number Of Ways To Arrive At Destination - Leetcode Solution

Companies:

LeetCode:  Number Of Ways To Arrive At Destination Leetcode Solution

Difficulty: Medium

Topics: dynamic-programming graph  

Problem Statement:

Given an integer n and a list of integer pairs "roads" representing the roads between the cities, where roads[i] = [ai, bi] means there is a road between the cities ai and bi. You want to reach the city n from city 1 on a trip and you follow these rules:

  1. You can only travel in the forward direction, i.e., you can only move to a city that is greater than the current city.
  2. You cannot move to any city that is not directly connected to the current city.
  3. You can take any number of trips to reach the destination city.

Return the number of different ways you can travel from city 1 to city n, modulo 10^9 + 7.

Example:

Input: n = 5, roads = [[1,2],[2,3],[3,4],[4,5]] Output: 5 Explanation: There are 5 ways to reach the destination: 1 -> 2 -> 3 -> 4 -> 5 1 -> 2 -> 3 -> 4 -> 5 1 -> 2 -> 3 -> 4 -> 5 1 -> 2 -> 3 -> 4 -> 5 1 -> 2 -> 3 -> 4 -> 5

Solution:

The problem can be solved using dynamic programming. We can use an array dp[i] to store the number of ways to reach city i from city 1.

dp[i] = sum(dp[j]) where j is the set of all cities that have a direct road to city i.

We can start by initializing dp[1] = 1 as there is only one way to reach city 1, i.e., start from city 1.

Then, for each city i, we can find all the cities that have a direct road to i and calculate dp[i] as the sum of dp[j] where j is the set of all such cities. Note that we need to take modulus of the sum at each step because the answer can be very large.

Finally, the answer will be dp[n] because we need to find the number of ways to reach city n from city 1.

Code:

class Solution { public: int countPaths(int n, vector<vector<int>>& roads) { vector<vector<int>> graph(n); for(auto road: roads){ graph[road[0]].push_back(road[1]); graph[road[1]].push_back(road[0]); } const int MOD = 1e9 + 7; vector<long long> dp(n, 0); dp[0] = 1; queue<int> q{{0}}; while(!q.empty()){ int cur = q.front(); q.pop(); for(auto neigh: graph[cur]){ if(neigh == cur + 1){ dp[neigh] += dp[cur]; dp[neigh] %= MOD; q.push(neigh); } } } return dp[n-1]; } };

Time Complexity: O(n+m) where n is the number of cities and m is the number of roads.

Space Complexity: O(n+m) for storing the graph.

Number Of Ways To Arrive At Destination Solution Code

1