华为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);
}
int main()
}
}
return-1;
}
{
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;
}
}
}