cpp dfs


  • 0
    B
    class Solution {
    public:
        int arrayNesting(vector<int>& nums) {
            vector<int> visited(nums.size(), -1);
            for (auto n: nums) {
                unordered_map<int, bool> current;
                if (visited[n] == -1) visited[n] = dfs(n, visited, nums , current);
            }
            return *max_element(visited.begin(), visited.end());    
        }
        int dfs(int n, vector<int> &visited, vector<int> &nums, unordered_map<int, bool> &current) {
            if (current.find(n) != current.end()) return 0;
            if (visited[n] != -1) return 1+visited[n];
            current[n] = true;
            visited[n] = 1 + dfs(nums[n], visited, nums, current);
            return visited[n];
        }
    };

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.