当前位置:   article > 正文

2014华为机试——两个城市之间的最多路径

华为机试找城市

题目:


代码:

  1. #include<vector>
  2. #include<iostream>
  3. using namespace std;
  4. void print(vector<int> &path,int& number){//打印一条路径
  5. cout<<"路径"<<number<<":";
  6. for(vector<int>::iterator iter=path.begin();iter!=path.end();iter++)
  7. cout<<*iter<<"-";
  8. }
  9. void FindPaths(int **p,int dim,int&pathNumber,vector<int>& path,bool* citylabel,int currentcity,int dest)
  10. {
  11. if(currentcity==dest)//当前城市为终点城市
  12. {pathNumber++;
  13. print(path,pathNumber);
  14. cout<<dest<<endl;
  15. return;}//递归终止条件
  16. else {
  17. citylabel[currentcity]=true;//标志当前城市已经存在搜索路径中(已经使用)
  18. vector<int> nextcity;
  19. for(int j=0;j<dim;j++)//遍历所有可能的下一个城市
  20. if(p[currentcity][j]==1&&!citylabel[j])
  21. nextcity.push_back(j);
  22. if(!nextcity.empty()){
  23. path.push_back(currentcity);//递归,遍历所有可能的下一个城市
  24. for(vector<int>::iterator it=nextcity.begin();it!=nextcity.end();it++)
  25. FindPaths(p,dim,pathNumber,path,citylabel,*it,dest);
  26. path.pop_back();
  27. }
  28. citylabel[currentcity]=false;//标志当前城市已经存在搜索路径中(已经使用)
  29. }
  30. }
  31. int main()
  32. {
  33. int dim,start,dest;//分别代表城市总数,起点城市,终点城市
  34. int pathNumber=0;//路径总数
  35. vector<int> path;
  36. cin>>dim>>start>>dest;
  37. bool *citylabel=new bool[dim];//某个城市是否已经在搜索路径中使用
  38. int **p=new int*[dim];//城市两两之间是否有路到达
  39. vector<int> nextcity;//可能的下一个城市
  40. for(int i=0;i<dim;i++)
  41. {
  42. p[i]=new int[dim];
  43. citylabel[i]=false;
  44. for(int j=0;j<dim;j++)
  45. {cin>>p[i][j];
  46. if(i==start&&p[i][j]==1&&j!=start)//可能的第2个城市
  47. nextcity.push_back(j);}
  48. }
  49. citylabel[0]=true;//起点设置为已存在于搜索路径中,即已经使用
  50. path.push_back(start);
  51. for(vector<int>::iterator it=nextcity.begin();it!=nextcity.end();it++)//以可能的第2个城市为基准,遍历
  52. FindPaths(p,dim,pathNumber,path,citylabel,*it,dest);
  53. cout<<"路径总数为"<<pathNumber<<endl;
  54. return 0;
  55. }


  当输入为:

              6 1 5
              1 0 0 0 1 0
              1 1 1 1 0 0
              0 0 1 0 1 1
              0 0 1 1 0 1
              0 0 0 1 1 1
              0 0 0 0 0 1
        输出为:路径总数为 9

      即下列9种情况:

      1 0 4 3 2 5
      1 0 4 3 5
      1 0 4 5
      1 2 4 3 5
      1 2 4 5
      1 2 5
      1 3 2 5
      1 3 2 4 5
      1 3 5

思想:

       1.简单的递归。设某个城市为当前城市,搜索其所有有路相连的下个城市,并存储至vector中。将当前城市设定为已经使用,遍历vector中存储的下一个城市,此时递归。一旦某个城市的所有可能的下一步方向遍历完,则将该城市设置为未在搜索路径中。

     2.注意递归终止条件的设定。

转载于:https://www.cnblogs.com/engineerLF/p/5393124.html

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/代码探险家/article/detail/792904
推荐阅读
相关标签
  

闽ICP备14008679号