题目:输入一个矩阵以及其行列值,矩阵中‘-’表示可以移动的坐标,‘#’表示障碍物不可以通过,‘B’表示起点,‘H’表示终点。在矩阵中可以上下左右移动,不可以斜线移动,求问是否存在从起点B到终点H的路径。
例如输入:
3 3
B - -
# # -
- H -
则应该输出YES
题目分析:题目是图论遍历问题,可以采用深度优先遍历的方法进行路径查找。采用回朔法、递归的思路解决问题。代码如下。
#include <iostream>
#include <vector>
using namespace std;
class Pos
{
public:
void set (int i, int j)
{
x = i, y = j;
}
int getx()
{
return x;
}
int gety()
{
return y;
}
private:
int x;
int y;
};
bool haspath(vector<char> & cv, vector<bool> & bv,int rows, int columns, int row, int column)
{
bool result = false;
if (row >= 0 && row < rows&&column >= 0 && column < columns&&!bv[row*columns + column])
{
if (cv[row*columns + column] == 'H')
return true;
if (cv[row*columns + column] == '#')
return false;
bv[row*columns + column] = true;
result = haspath(cv, bv, rows, columns, row - 1, column)
|| haspath(cv, bv, rows, columns, row, column + 1)
|| haspath(cv, bv, rows, columns, row + 1, column)
|| haspath(cv, bv, rows, columns, row, column - 1);
//观察中间结果用打印数据
/* for (int i = 0; i < rows; ++i)
{
for (int j = 0; j < columns; ++j)
cout << bv[i*columns + j] << " ";
cout << endl;
}
cout << endl;*/
if (!result)
bv[row*columns + column] = false;
}
return result;
}
int main()
{
int rows, columns;
cin >> rows >> columns;
Pos Begin;
vector<char> cvect;
vector<bool> bvect;
char temp;
for (int i = 0; i < rows; ++i)
for (int j = 0; j < columns; ++j)
{
cin >> temp;
cvect.push_back(temp);
if (temp == 'B')
Begin.set(i, j);
bvect.push_back(false);
}
bool possible;
possible=haspath(cvect,bvect,rows,columns,Begin.getx(),Begin.gety());
if(possible)
cout << "YES"<<endl;
else
cout << "NO" << endl;
}
测试结果如下图:
代码中注释的部分打印了记录路径的容器,如取消注释打印结果如下:
0 1 1 0 1 1
0 1 0 1 1 0
1 1 0 1 0 0
1 0 1 1 0 0
1 1 1 0 0 0
0 1 1 0 1 0
0 1 0 1 1 0
1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