DFS解决下述所有问题:
寻找出口的方案个数+最短路径的距离+最短路径坐标
#include<iostream>
#include<vector>
using namespace std;
vector<pair<int, int>>ans;
vector<pair<int, int>>temp;
int row, col;
int num;
int minstep = 99999;
int step = 0;//距离
int path = 0;//方案总数
int dx[] = { 0,0,-1,1 };
int dy[] = { 1,-1,0,0 };
vector<vector<int>>v;
vector<vector<int>>a(100,vector<int>(100,0));
void dfs(int x,int y,int step)
{
temp.push_back({ x,y });
if (x == row - 1 && y == col - 1)
{
path++;
ans = temp;
if (step < minstep)
{
minstep = step;
}
return;//找到了就结束
}
for (int k = 0; k < 4; k++)
{
int tx = x + dx[k];
int ty = y + dy[k];
if (tx<0 || ty<0 || tx>row - 1 || ty>col - 1 || v[tx][ty] == 1 || a[tx][ty] == 1)
continue;
a[tx][ty] = 1;
dfs(tx, ty, step + 1);
temp.pop_back();//没找到就回溯
a[tx][ty] = 0;
}
return;
}
int main()
{
while (cin >> row >> col)
{
for (int i = 0; i < row; i++)
{
vector<int>v1(col,0);
for (int j = 0; j < col; j++)
{
cin >> v1[j];
}
v.push_back(v1);
}
a[0][0] = 1;
dfs(0,0,step);
cout << path << endl;
cout << minstep << endl;
for (auto t : ans)
cout <<"(" <<t.first<<","<<t.second<<")" << endl;
}
return 0;
}
结果展示: