迷宫-最短路径

华为oj和剑指offer都有相关题型,但针对不同题型会有不同解法,有动态规划取最优解和广度、深度遍历的方法。


这里针对华为oj上的原题,以及16年华为大牛专场的笔试题。

所求的是地图中的最短路径,但并不是只有一条路径。

华为最早的oj题里是只有一条路径,那么用深度遍历是最快捷的。

但如果有多条路径,需要就最短路径。还是要用广度遍历。

深度遍历无法保证求得最优解。

#include<iostream>
#include<math.h>
#include<string>
#include<vector>
#include<algorithm>
#include<sstream>
#include<queue>

using namespace std;



struct Node

{

int x;


int y;


int step;


Node(int x1, int y1, int step1) :x(x1), y(y1), step(step1){}


};

int BFS(vector<vector<int>>rec, vector<vector<int>>dp,int n)

{


Node node(0, 0, 0);


queue<Node> q;


while (!q.empty())q.pop();


q.push(node);

vector<vector<int>>stepArr(4, vector<int>(2, 0));

stepArr[0][0] = 0;

stepArr[0][1] = 1;

stepArr[1][0] = 0;

stepArr[1][1] = -1;

stepArr[2][0] = 1;

stepArr[2][1] = 0;

stepArr[3][0] = -1;

stepArr[3][1] = 0;


while (!q.empty())


{


node = q.front();


q.pop();


if (node.x == n - 1 && node.y == n - 1)


{


return node.step;


}


dp[node.x][node.y] = 1;


for (int i = 0; i<4; i++)


{


int x = node.x + stepArr[i][0];


int y = node.y + stepArr[i][1];


if (x >= 0 && y >= 0 && x<n&&y<n&&rec[x][y] == 0 && dp[x][y] == 0)


{


dp[x][y] = 1;


Node next(x, y, node.step + 1);


q.push(next);


}


}


}


return-1;


}

int main()
{

int n;

while (cin >> n)

{

vector<vector<int>>rec(n + 1, vector<int>(n + 1, 0));

vector<vector<int>>dp(n + 1, vector<int>(n + 1, 0));

for (int i = 0; i < n; i++)

{

for (int j = 0; j < n; j++)

{

int tmp = 0;

cin >> tmp;

rec[i][j] = tmp;

}

}

if (rec[0][0] == 1 || rec[n - 1][n - 1] == 1)

cout << -1 << endl;

else{

cout << BFS(rec, dp, n) << endl;


}

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值