I am solving this problem using DSU.
But it fails on this test case, I can’t find the mistake.
Is my logic incorrect or some bug?
I saw that this can be easily solved using recursion(DFS) and queue(BFS).
class Solution
{
public:
vector<int> parent;
void makeSets()
{
for (int i = 0; i < parent.size(); i++)
{
parent[i] = i;
}
}
int findSet(int a)
{
if (a == parent[a])
{
return a;
}
return parent[a] = findSet(parent[a]);
}
void unionSets(int a, int b)
{
a = findSet(a);
b = findSet(b);
if (a != b)
{
parent[a] = b;
}
}
bool canReach(vector<int> &arr, int start)
{
parent.assign(arr.size(), 0);
makeSets();
int n = arr.size();
vector<int> zeroIndices;
for (int i = 0; i < n; i++)
{
int x = i + arr[i];
int y = i - arr[i];
if (arr[i] == 0)
{
zeroIndices.push_back(i);
continue;
}
if (0 <= x && x <= n - 1)
{
unionSets(i, x);
}
if (0 <= y && y <= n - 1)
{
unionSets(i, y);
}
}
for (auto i : zeroIndices)
{
if (findSet(i) == findSet(start))
{
return true;
}
}
return false;
}
};
Any help would be great.
Thanks
@ssrivastava990 what do you think?