← Home

1377. Frog Position After T Seconds

LeetCode article · C++ solution
Website made by wuisabel-gif · Original C++ code by keineahnung2345
graph traversalC++Markdown
137

I like to read this solution as a small machine: keep the useful information, throw away the noise. For 1377. Frog Position After T Seconds, the solution in this repository is mainly a graph traversal solution.

Guide

What?

The first job is to translate the English prompt into state, transition, and stopping conditions. Instead of trying to be clever immediately, read the code as a sequence of questions:

  • What state are we keeping?
  • How do we move from one state to the next?
  • When do we know the answer is already determined?

For this file, the main tools are: graph traversal.

Guide

When?

This pattern shows up when the brute force version has too many repeated checks, too many possible branches, or too much bookkeeping to do by hand. The accepted code reduces that pressure by storing exactly the information that remains useful later.

The important function names to track are dfs, frogPosition, visited, prob.

Guide

Why?

The code is doing bookkeeping so your brain does not have to keep the entire search space open at once.

  • A map keeps the lookup side cheap; the code pays a little memory to avoid repeated searching.
  • The queue gives the solution a level-by-level or frontier-style traversal.
  • The two-dimensional vector is the memory of the solution: grid state, DP state, or adjacency shape.
  • The final return is not magic; it is the invariant after the loops or recursion have finished doing their accounting.

Guide

How?

Walk through the solution in this order:

  1. Initialize the memory or helper structure.
  2. Process candidates in the order the invariant expects.
  3. Update the answer only when the current state is valid.
  4. Return the value that represents the fully processed input.

The most important competitive-programming habit here is to trust the invariant. Once the invariant is right, the loops become much less scary.

Guide

Complexity

  • Time: O(n) to O(n log n), depending on the dominant loop or data structure operation
  • Space: O(n) in the usual case for auxiliary containers or recursion

Guide

C++ Solution

Your submission

The accepted solution

solution.cpp
01//Runtime: 44 ms, faster than 28.71% of C++ online submissions for Frog Position After T Seconds.
02//Memory Usage: 10.8 MB, less than 100.00% of C++ online submissions for Frog Position After T Seconds.
03class Solution {
04public:
05    // unordered_map<int, vector<int>> children;
06    vector<vector<bool>> adj;
07    vector<bool> visited;
08    int target;
09    vector<int> path;
10    
11    bool dfs(int node){
12        if(node == target){
13            path.insert(path.begin(), node);
14            return true;
15        }
16        // for(int child : children[node]){
17        for(int child = 1; child <= (int)adj.size()-1; child++){
18            if(!adj[node][child] || visited[child]) continue;
19            // cout << node << "----" << child << endl;
20            visited[child] = true;
21            //cut the reverse directed edge
22            adj[child][node] = false;
23            if(dfs(child)){
24                path.insert(path.begin(), node);
25                return true;
26            }
27        }
28        return false;
29    };
30    
31    double frogPosition(int n, vector<vector<int>>& edges, int t, int target) {
32        adj = vector(n+1, vector(n+1, false)); //0 is for padding
33        visited = vector(n+1, false); //need to use this because the tree is undirected
34        
35        for(vector<int>& edge : edges){
36            // children[edge[0]].push_back(edge[1]);
37            adj[edge[0]][edge[1]] = adj[edge[1]][edge[0]] = true;
38        }
39        this->target = target;
40        
41        dfs(1);
42        visited[1] = true;
43        
44        if(t < (int)path.size()-1){
45            //not enough time
46            return 0.0;
47        }
48        // else if(t > path.size()-1 && children[target].size() > 0){
49        else if(t > path.size()-1 && accumulate(adj[target].begin()+1, adj[target].end(), 0) > 0){
50            //too much time, and the target has children
51            //so the frog won't stop at target
52            return 0.0;
53        }
54        
55        // cout << "path length: " << (int)path.size()-1 << endl;
56        double ans = 1.0;
57        for(int i = 0; i < (int)path.size()-1; i++){
58            // ans *= 1.0/children[path[i]].size();
59            int childCount = accumulate(adj[path[i]].begin()+1, adj[path[i]].end(), 0);
60            // cout << "node: " << path[i] << ", children: " << childCount << endl;
61            ans *= 1.0/childCount; 
62            // cout << path[i] << " ";
63        }
64        // cout << endl;
65        
66        return ans;
67    }
68};
69
70//BFS
71//https://leetcode.com/problems/frog-position-after-t-seconds/discuss/532505/Java-Straightforward-BFS-Clean-code-O(N)
72//Runtime: 24 ms, faster than 69.53% of C++ online submissions for Frog Position After T Seconds.
73//Memory Usage: 11.3 MB, less than 100.00% of C++ online submissions for Frog Position After T Seconds.
74class Solution {
75public:
76    double frogPosition(int n, vector<vector<int>>& edges, int t, int target) {
77        vector<vector<int>> children(n+1);
78        vector<bool> visited(n+1, false);
79        vector<double> prob(n+1, 0.0);
80        queue<int> q;
81        
82        for(vector<int>& edge : edges){
83            children[edge[0]].push_back(edge[1]);
84            children[edge[1]].push_back(edge[0]);
85        }
86        
87        q.push(1);
88        visited[1] = true;
89        prob[1] = 1.0;
90        //we can only go to "t"th levels
91        while(!q.empty() && t-- > 0){
92            for(int levelCount = q.size(); levelCount > 0; levelCount--){
93                int node = q.front(); q.pop();
94                int nextLevelCount = 0;
95                for(int child : children[node]){
96                    if(!visited[child])nextLevelCount++;
97                }
98                for(int child : children[node]){
99                    if(visited[child]) continue;
100                    visited[child] = true;
101                    prob[child] = prob[node] / nextLevelCount;
102                    q.push(child);
103                }
104                if(nextLevelCount > 0){
105                    //current node is not leaf
106                    prob[node] = 0.0;
107                }
108            }
109        }
110        return prob[target];
111    }
112};

Cost

Complexity

Time
O(n) to O(n log n), depending on the dominant loop or data structure operation
Dominated by the main traversal, recursion, or data-structure operations in the code.
Space
O(n) in the usual case for auxiliary containers or recursion
Auxiliary state plus the answer structure where the problem requires one.