Advertisement
Guest User

dfs

a guest
Feb 19th, 2020
100
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.99 KB | None | 0 0
  1. int main()
  2. {
  3. #ifndef ONLINE_JUDGE
  4. //freopen("cin.txt","r",stdin);
  5. //freopen("cout.txt","w",stdout);
  6. #endif // ONLINE_JUDGE
  7. //speed
  8. int t=Int;
  9. while(t--){
  10. int n=Int,e=Int;
  11. vector<int> adj[n+1];
  12. for(int a=1;a<=e;a++){
  13. int x=Int,y=Int;
  14. if(x>y)swap(x,y);
  15. adj[x].pb(y);
  16. }
  17. stack<int> dfs;
  18. dfs.push(1);
  19. int distance[n+1]={0};
  20. int color[n+1]={0};
  21. while(!dfs.empty()){
  22. int top=dfs.top();
  23. bool found=false;
  24. for(int a=0;a<adj[top].size();a++){
  25. int u=top,v=adj[top][a];
  26. if(color[v]==0){
  27. dfs.push(v);
  28. distance[v]=distance[u]+1;
  29. color[v]=1;
  30. found=true;
  31. }
  32. }
  33. if(!found){
  34. dfs.pop();
  35. }
  36. }
  37. cout<<distance[n]<<endl;
  38. }
  39. r0;
  40. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement