1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
| class Solution { public: bool canCross(vector<int>& stones) { const int n = stones.size(); vector<unordered_map<int, bool>> m(n); function<bool(int, int)> dfs = [&](int i, int lastDist) { if (i == n - 1) return true; if (m[i].find(lastDist) != m[i].end()) return m[i][lastDist]; for (int currDist = lastDist - 1; currDist <= lastDist + 1; ++currDist) { if (currDist > 0) { int j = lower_bound(stones.begin(), stones.end(), currDist + stones[i]) - stones.begin(); if (j != n && stones[j] == stones[i] + currDist && dfs(j, currDist)) { return m[i][lastDist] = true; } } } return m[i][lastDist] = false; }; return dfs(0, 0); } };
|