主题:一些有关递归回溯的程序
//
// road.cpp acm消防车题(91.A)
// lanjingquan 2002.7.20
///////////////////////////////////////////
#include"road.h"
ROAD::ROAD()
{
init();
times2=1;
record=new int[22];
}
bool ROAD::GetDataAndFind(char* file)
{
ifstream input(file,ios::nocreate);
int row,col;
while(!input.eof())
{
input>>goal;
input>>row>>col;
while(row!=0&&col!=0)
{
data[row][col]=1;
data[col][row]=1;
input>>row>>col;
}
FindRoad();
init();
}
return true;
}
bool ROAD::FindRoad(const int first,int& idx)
{
int n=idx;
record[n++]=first;
if(first==goal)
{
for(int j=0;j<idx;j++)
cout<<record[j]<<" ";
cout<<goal<<endl;
times++;
return true;
}
for(int i=1;i<=21;i++)
if(data[first][i]==1&&data[i][i]==0)
{
data[i][i]=1;
FindRoad(i,n);
data[i][i]=0;
}
return true;
}
bool ROAD::FindRoad()
{
cout<<"CASE# "<<(times2++)<<":"<<endl;
int i=0;
data[1][1]=1;
FindRoad(1,i);
cout<<"There are "<<times
<<" routes from the firestation to streetcorner "
<<goal<<"."<<endl<<endl;
return true;
}
bool ROAD::init()
{
for(int i=0;i<=21;i++)
for(int j=0;j<=21;j++)
data[i][j]=0;
goal=0;
times=0;
return true;
}
ROAD::~ROAD()
{
delete[] record;
}
// road.cpp acm消防车题(91.A)
// lanjingquan 2002.7.20
///////////////////////////////////////////
#include"road.h"
ROAD::ROAD()
{
init();
times2=1;
record=new int[22];
}
bool ROAD::GetDataAndFind(char* file)
{
ifstream input(file,ios::nocreate);
int row,col;
while(!input.eof())
{
input>>goal;
input>>row>>col;
while(row!=0&&col!=0)
{
data[row][col]=1;
data[col][row]=1;
input>>row>>col;
}
FindRoad();
init();
}
return true;
}
bool ROAD::FindRoad(const int first,int& idx)
{
int n=idx;
record[n++]=first;
if(first==goal)
{
for(int j=0;j<idx;j++)
cout<<record[j]<<" ";
cout<<goal<<endl;
times++;
return true;
}
for(int i=1;i<=21;i++)
if(data[first][i]==1&&data[i][i]==0)
{
data[i][i]=1;
FindRoad(i,n);
data[i][i]=0;
}
return true;
}
bool ROAD::FindRoad()
{
cout<<"CASE# "<<(times2++)<<":"<<endl;
int i=0;
data[1][1]=1;
FindRoad(1,i);
cout<<"There are "<<times
<<" routes from the firestation to streetcorner "
<<goal<<"."<<endl<<endl;
return true;
}
bool ROAD::init()
{
for(int i=0;i<=21;i++)
for(int j=0;j<=21;j++)
data[i][j]=0;
goal=0;
times=0;
return true;
}
ROAD::~ROAD()
{
delete[] record;
}