i really cant understand how to do this problem using graphs and dfs.
can anyone please explain it to me?
thankss.
here is the link
anyone???
void solve()
{
int n, m;
sc(n), sc(m); // inputs
vector<int> mark(N + 10, -1); // N is the max-limit 1e4
mark[n] = 0; // zero steps to reach 'n'
queue<pair<int, int>>q;
q.push({n, 0});
while (!q.empty()) {
auto top = q.front();
q.pop();
if (top.F * 2 <= N && mark[top.F * 2] == -1) {
mark[top.F * 2] = top.S + 1;
q.push({top.F * 2, top.S + 1});
}
if (top.F - 1 >= 0 && mark[top.F - 1] == -1) {
mark[top.F - 1] = top.S + 1;
q.push({top.F - 1, top.S + 1});
}
}
cout<<mark[m]<<endl;
}
mark each step only once
Here is a simple implementation with all 3 possible cases:
2 Likes