while(!get_goal) { memset(vis,0,sizeof(vis)); path.clear(); ids(strt,lim++); } void ids(int node, int lim) { dls_level++; ///This segment works to return if goal acheived. (Main modification of Standerd algo). if(get_goal) return; if(node==goal) { path.push_back(node); get_goal=true; return; } path.push_back(node); vis[node]=1; for(int i=1;i<=n;i++) { if(graph[node][i] && !vis[i]) { if(dls_level<lim) ids(i,lim); } } dls_level--; }