面试题:
设有N个城市,矩阵M为N*N的矩阵,表示各个城市间的通路状况,例如,若城市A(0=< A <N)与城市B(0=< A <N)之间若为通路,则用矩阵元素M[A][B] = 1表示,否则M[A][B] = 0;现在输入城市数量N,出发点src和目的地dest,求src到dest有几种走法,即src到dest的总路径数。
#include <iostream>
#include <vector>
using namespace std;
void countOfRoute(int src,int dest,vector<bool*> MaMatrixDL,bool* hasNoneRoute,int &count,int N)
{
//算法思想:遍历尚未访问过的节点,若它与前一节点之间是通路,则判断:
// 若该访问节点即为目的地,则让总路径数加一
// 若该访问节点非目的地,则将出发节点置为该节点,重新遍历到现在为止尚未访问的节点
//(用矩阵hasNoneRoute表示尚未访问的节点)
for (int iter = 0;iter<N;iter++)
{
if (MaMatrixDL[src][iter]&&hasNoneRoute[iter])
{
if (iter == dest)
count++;
else
{
src = iter;
hasNoneRoute[iter] = false;
countOfRoute(src,dest,MaMatrixDL,hasNoneRoute,count,N);
hasNoneRoute[iter] = true;
}
}
}
return;
}
void main()
{
int N,A,B;
cout<<"请输入城市数量N,出发点A,目的地B"<<endl;
cin>>N>>A>>B;
vector<bool*> MatrixDL(N);
int i = 0,j = 0;
while(i<N)
{
MatrixDL[i] = new bool[N];
while (i<N)
{
cin>>MatrixDL[i][j++];
if(j>=N)
break;
}
j = 0;
i++;
}
//设置未访问的节点(编号为0~N-1)为true
bool* hasNoRoute = new bool[N];
i = 0;
while (i<N)
{
if (i!=A)
{
hasNoRoute[i] = true;
}
else
hasNoRoute[i] = false;
i++;
}
//用count计数,
int count = 0;
countOfRoute(A,B,MatrixDL,hasNoRoute,count,N);
cout<<"总路径数量:";
cout<<count<<endl;
i = 0;
while(i<N)
{
delete [] MatrixDL[i];
MatrixDL[i++] = NULL;
}
delete [] hasNoRoute;
}