华为机试 是否存在路径(深度优先遍历、回朔法、递归)

题目:输入一个矩阵以及其行列值,矩阵中‘-’表示可以移动的坐标,‘#’表示障碍物不可以通过,‘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;
}

测试结果如下图:

这里写图片描述

代码中注释的部分打印了记录路径的容器,如取消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0 1 1

0 1 1 0 0 0
0 1 0 0 0 0
1 1 0 0 0 0
1 0 1 1 1 1
1 1 1 0 1 1

0 1 1 0 0 0
0 1 0 0 0 0
1 1 0 0 0 0
1 0 1 1 1 1
1 1 1 0 1 1

0 1 1 0 0 0
0 1 0 0 0 0
1 1 0 0 0 0
1 0 1 1 1 1
1 1 1 0 1 1

0 1 1 0 0 0
0 1 0 0 0 0
1 1 0 0 0 0
1 0 1 1 1 1
1 1 1 0 1 1
可以看出,虽然解决了路径是否存在的问题,但这并不是最短路径。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值