https://leetcode.com/problems/shortest-path-visiting-all-nodes/
Link to the Question
This is the code I wrote in C++.
I have a variable "visited" to track the nodes that have been visited.
I have set the ith bit when I visit that node.
It is Passing 50/51 test cases and failing in only one particular case.
===========================
Input -> [[2,3,4,8],[8],[0],[0,8],[0,5,6],[4,7],[4],[5],[0,3,1]]
Expected -> 10
Output -> 11
Can anyone please tell me where am I faltering?
class Solution {
public:
int func(int i, int visited, vector<vector<int>>&graph, vector<vector<int>>&dp, int&n, set<pair<int,int>>&seen)
{
if(dp[visited][i]!=-1) return dp[visited][i];
if(visited == (1<<n)-1) return 0;
if(seen.find(make_pair(visited, i)) != seen.end()) return 10000;
seen.insert(make_pair(visited, i));
int ans= 10000;
for(auto x:graph[i])
{
if(ans > 1+func(x, visited|(1<<x), graph, dp, n, seen))
{
ans = 1+func(x,visited|(1<<x), graph, dp, n, seen);
}
}
return dp[visited][i] = ans;
}
int shortestPathLength(vector<vector<int>>& graph)
{
int n=graph.size();
int ans = 10000;
for(int i=0;i<n;i++)
{
int visited = 0;
vector<vector<int>> dp ( (1<<n) ,vector<int>(n,-1));
set<pair<int,int>> seen;
ans = min( ans, func(i, 0|(1<<i), graph, dp, n, seen) );
}
return ans;
}
};