矩阵的最短路径问题

今天字节二面,面试官给了一个笔试题,因为时间仓促,也没有提前准备,就挂掉了,回来仔细思考了一下做了个简单的解答,

题目是这样的,一个mxn的二维矩阵,均为正元素,且对应的元素代表该处的代价,求从(0,0)到(m,n)的最短路径。

code如下:

#include <iostream>
#include <cstring>
#include <vector>
#include <queue>

using namespace std;

class Solution {
public:
typedef struct Index{
Index(){x = 0; y = 0;};
Index(int xx, int yy):x(xx),y(yy){}
int x, y;
};
std::vector<std::pair<int ,int>> shortestRoad(const vector<vector<int>> &matrix) {
std::vector<std::pair<int, int>> answer;
int m = matrix.size();
if(m == 0) return answer;
const int maxvale = 10000000;
int n = matrix[0].size();
vector<vector<int>> table = matrix;
for(size_t i = 0; i < table.size(); i++){
for(size_t j = 0; j < table[i].size(); j++){
table[i][j] = maxvale;
}
}

std::queue<Index> q;

Index target(m-1, n-1);
table[m-1][n-1] = std::min(maxvale, matrix[m-1][n-1]);

q.push(target);


while (!q.empty()){
Index top = q.front();
q.pop();

if(top.x == 0 && top.y == 0){
break;
}

if(top.x - 1 >= 0){
if(table[top.x-1][top.y] > table[top.x][top.y] + matrix[top.x-1][top.y]){
table[top.x - 1][top.y] = table[top.x][top.y] + matrix[top.x-1][top.y];
q.push(Index(top.x-1, top.y));
}
}
if(top.x + 1 < m){
if(table[top.x+1][top.y] > table[top.x][top.y] + matrix[top.x+1][top.y]){
table[top.x + 1][top.y] = table[top.x][top.y] + matrix[top.x+1][top.y];
q.push(Index(top.x+1, top.y));
}
}
if(top.y - 1 >= 0){
if(table[top.x][top.y-1] > table[top.x][top.y] + matrix[top.x][top.y-1]){
table[top.x][top.y-1] = table[top.x][top.y] + matrix[top.x][top.y-1];
q.push(Index(top.x, top.y-1));
}
}
if(top.y + 1 < n){
if(table[top.x][top.y+1] > table[top.x][top.y] + matrix[top.x][top.y+1]){
table[top.x][top.y+1] = table[top.x][top.y] + matrix[top.x][top.y+1];
q.push(Index(top.x, top.y+1));
}
}
}

Index index(0, 0);
answer.push_back(std::pair<int, int>(0, 0));
while (index.x != m-1 || index.y != n-1){
int maxcost = maxvale;
Index cur = index;
if(index.x - 1 >= 0){
if(maxcost > table[index.x-1][index.y]){
maxcost = table[index.x-1][index.y];
cur = index;
cur.x = cur.x - 1;
}
}
if(index.x + 1 < m){
if(maxcost > table[index.x+1][index.y]){
maxcost = table[index.x+1][index.y];
cur = index;
cur.x = cur.x + 1;
}
}
if(index.y - 1 >= 0){
if(maxcost > table[index.x][index.y-1]){
maxcost = table[index.x][index.y-1];
cur = index;
cur.y = cur.y - 1;
}
}
if(index.y + 1 < n){
if(maxcost > table[index.x][index.y+1]){
maxcost = table[index.x][index.y+1];
cur = index;
cur.y = cur.y + 1;
}
}
index = cur;
answer.push_back(std::pair<int, int>(index.x, index.y));
}
return answer;
}
};

vector<vector<int>> matrix = {
{1, 4, 7, 5, 3, 6, 2, 2},
{5, 3, 6, 8, 9, 7, 6, 1},
{3, 2, 5, 1, 6, 4, 7, 8},
{9, 5, 3, 6, 8, 7, 4, 1},
{6, 3, 8, 6, 3, 2, 5, 8}}
;

int main() {
Solution s = Solution();
vector<std::pair<int, int>> answer = s.shortestRoad(matrix);
for(size_t i = 0; i < answer.size(); i++){
std::cout<<"("<<answer[i].first<<", "<<answer[i].second<<")"<<std::endl;
}
return 0;}



原文地址:https://www.cnblogs.com/cfzhang/p/15122398.html