fork download
  1. #include <iostream>
  2. #include <vector>
  3. #include <map>
  4. #include <queue>
  5. using namespace std;
  6.  
  7. struct node
  8. {
  9. int x;
  10. vector<int> V;
  11. node(int x1)
  12. {
  13. x=x1;
  14. }
  15. };
  16.  
  17.  
  18. int main() {
  19.  
  20. int n,m;
  21. cin>>n>>m;
  22.  
  23. map<int,map<int,int> > Map;
  24.  
  25. for(int i=0;i<m;i++)
  26. {
  27. int x,y;
  28. cin>>x>>y;
  29. Map[x-1][y-1]=1;
  30. Map[y-1][x-1]=1;
  31. }
  32.  
  33. int visited[n];
  34. for(int i=0;i<n;i++)
  35. {
  36. visited[i]=0;
  37. }
  38.  
  39. queue<node*> Q;
  40. Q.push(new node(0));
  41. vector<int> ans;
  42. while(!Q.empty())
  43. {
  44. node* x = Q.front();
  45. Q.pop();
  46. visited[x->x]=1;
  47.  
  48. if(x->x == n-1)
  49. {
  50. ans=x->V;
  51. ans.push_back(n-1);
  52. break;
  53. }
  54.  
  55. for(auto it=Map[x->x].begin();it!=Map[x->x].end();it++)
  56. {
  57. node* nod = new node(it->first);
  58. for(int i=0;i<x->V.size();i++)
  59. {
  60. nod->V.push_back(x->V[i]);
  61. }
  62. nod->V.push_back(x->x);
  63. Q.push(nod);
  64. }
  65. }
  66.  
  67. cout<<ans.size()<<endl;
  68. for(int i=0;i<ans.size();i++)
  69. {
  70. cout<<ans[i]+1<<" ";
  71. }
  72. cout<<endl;
  73.  
  74. return 0;
  75. }
Success #stdin #stdout 0s 5280KB
stdin
5 5
1 2
1 3
1 4
2 3
5 4
stdout
3
1 4 5