题目:
如下图,某物流派送员p,需要给 a、b、c、d. 4个快递点派送包裹,请问派送员需要选择什么样的路线,才能完成最短路程的派送。假设如图派送员的起点坐标(0,0),派送路线只能沿着图中的方格边行驶,每个小格都是正方形,且边长为1,如p到d的距离就是4。随机输入n个派送点坐标,求输出最短派送路线值(从起点开始完成n个点派送并回到起始点的距离)。
输入示例:
2,2
2,8
4,4
7,2
输出:
30
C++代码
//快递员最短路径
#include <iostream>
#include <iterator>
#include <cmath>
#include <algorithm>
#include <climits>
#include <string>
//#include <utility>
using namespace std ;
struct Point{
Point(int a,int b){x=a;y=b;}
Point()=default;
int x ,y;
bool flag = false;
int distance(Point & p){
return abs(x-p.x)+abs(y-p.y);
}
};
Point start(0,0);
Point ps[4];
int minPath = INT_MAX ;
bool allVisted(){
return all_of(begin(ps),end(ps),[](const Point&p){return p.flag;});
}
void shortestPath(int nowPath,Point & preP){
if(allVisted()){//结束条件 end condition
int tmp = start.distance(preP)+nowPath;
if(minPath > tmp){
minPath = tmp;
}
return ;
}
for(int i=0;i<4;i++){
if(ps[i].flag==false){
ps[i].flag = true;
nowPath += ps[i].distance(preP);
shortestPath(nowPath,ps[i]);//递归
nowPath -= ps[i].distance(preP); //回溯
ps[i].flag = false;
}
}
}
int main(){
for(int i=0;i<4;i++){
string line;
getline(cin,line);
ps[i].x = stoi(string(line,0,line.find(',')));
ps[i].y = stoi(string(line,line.find(',')+1));
cout<<ps[i].x<<" "<<ps[i].y<<endl;
}
shortestPath(0,start);
cout<<minPath<<endl;
}