← Home

403. Frog Jump

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

The trick here is to name the state correctly, then let the implementation follow. For 403. Frog Jump, the solution in this repository is mainly a graph traversal solution.

Guide

What?

We want to turn the problem statement into a smaller set of decisions the computer can repeat safely. 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, dynamic programming.

The notes already sitting in the source point us in the right direction:

  • BFS, unordered_set

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 canCross.

Guide

Why?

The solution works because it narrows the problem until every update has a clear reason to exist.

  • A map keeps the lookup side cheap; the code pays a little memory to avoid repeated searching.
  • A set is doing the membership or uniqueness work, which keeps the main loop readable.
  • 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.

Guide

How?

Walk through the solution in this order:

  1. Read the setup variables first.
  2. Follow the main loop or recursive helper next.
  3. Watch where invalid states get skipped.
  4. Check which value survives to the return statement.

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//BFS, unordered_set
02//Runtime: 1836 ms, faster than 5.05% of C++ online submissions for Frog Jump.
03//Memory Usage: 42.3 MB, less than 34.48% of C++ online submissions for Frog Jump.
04/*
05if using ordinary set:
06//TLE
07//25 / 39 test cases passed.
08*/
09struct pair_hash {
10    inline std::size_t operator()(const std::pair<int,int> & v) const {
11        return v.first*31+v.second;
12    }
13};
14
15class Solution {
16public:
17    bool canCross(vector<int>& stones) {
18        int goal = stones.back();
19        
20        unordered_map<int, int> pos2idx;
21        for(int i = 0; i < stones.size(); ++i){
22            pos2idx[stones[i]] = i;
23        }
24        
25        queue<pair<int, int>> q;
26        pair<int, int> cur = {0, 1};
27        unordered_set<pair<int, int>, pair_hash> visited;
28        
29        q.push(cur);
30        visited.insert(cur);
31        
32        while(!q.empty()){
33            cur = q.front(); q.pop();
34            int pos = cur.first, step = cur.second;
35            // cout << pos << ", " << step << endl;
36            if(pos == goal) return true;
37            
38            int npos = pos+step;
39            int nstep;
40            
41            //next position must be a stone
42            if(find(stones.begin(), stones.end(), npos) == stones.end()){
43                continue;
44            }
45            
46            for(int i = -1; i <= 1; ++i){
47                nstep = step+i;
48                if(nstep <= 0) continue;
49                if(visited.find({npos, nstep}) == visited.end()){
50                    visited.insert({npos, nstep});
51                    q.push({npos, nstep});
52                }
53            }
54        }
55        
56        return false;
57    }
58};
59
60//unordered_map
61//https://leetcode.com/problems/frog-jump/discuss/88824/Very-easy-to-understand-JAVA-solution-with-explanations
62//Runtime: 392 ms, faster than 33.90% of C++ online submissions for Frog Jump.
63//Memory Usage: 44.3 MB, less than 29.73% of C++ online submissions for Frog Jump.
64class Solution {
65public:
66    bool canCross(vector<int>& stones) {
67        if(stones.size() == 0) return true;
68        set<int> sstones(stones.begin(), stones.end());
69        stones = vector<int>(sstones.begin(), sstones.end());
70        
71        int goal = stones.back();
72        // cout << "goal: " << goal << endl;
73        
74        unordered_map<int, unordered_set<int>> pos2steps;
75        //the first position is always 0
76        pos2steps[0].insert(1);
77        
78        int n = stones.size();
79        for(int i = 0; i < n; ++i){
80            int pos = stones[i];
81            for(int step : pos2steps[pos]){
82                int npos = pos + step;
83                if(npos == goal) return true;
84                if(sstones.find(npos) == sstones.end()){
85                    //there is no stone here
86                    continue;
87                }
88                for(int nstep = step-1; nstep <= step+1; ++nstep){
89                    if(nstep <= 0) continue;
90                    pos2steps[npos].insert(nstep);
91                }
92            }
93        }
94        
95        return false;
96    }
97};
98
99//DP
100//https://leetcode.com/problems/frog-jump/discuss/193816/Concise-and-fast-DP-solution-using-2D-array-instead-of-HashMap-with-text-and-video-explanation.
101//Runtime: 260 ms, faster than 52.89% of C++ online submissions for Frog Jump.
102//Memory Usage: 18.3 MB, less than 70.73% of C++ online submissions for Frog Jump.
103class Solution {
104public:
105    bool canCross(vector<int>& stones) {
106        if(stones.size() == 0) return true;
107        set<int> sstones(stones.begin(), stones.end());
108        stones = vector<int>(sstones.begin(), sstones.end());
109        
110        int goal = stones.back();
111        
112        int n = stones.size();
113        
114        /*
115        dp[i][j]: at ith stone(i is for index, not position!), 
116        (the index of i is 0-based),
117        whether we can jump with distance j
118        n+1: at position i, the maximum distance we can jump is i+1
119        */
120        vector<vector<bool>> dp(n, vector<bool>(n+1, false));
121        
122        //base case: at position 0, we can jump 1 distance forward
123        dp[0][1] = true;
124        
125        for(int end = 1; end < n; ++end){
126            for(int start = 0; start < end; ++start){
127                //start and end are index, here convert them into actual positions
128                int dist = stones[end] - stones[start];
129                if(dist >= n+1 || !dp[start][dist]) continue;
130                if(end == n-1) return true;
131                for(int ndist = dist-1; ndist <= dist+1; ndist++){
132                    if(ndist <= 0) continue;
133                    dp[end][ndist] = true;
134                }
135            }
136        }
137        
138        return false;
139    }
140};

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.