In the latest IEEE Xtreme Competition, a problem I’ve tried to solve is this,
Input Two points p1(x1,y1) , p2(x2,y2) you must find the length of shortest path from p1 to p2,
for example if p1(1,1) , p2(4,4) then the shortest path has lenght of 9 edges,

I did something like depth first search, it works great if the distance between the two point is small, and take long time for example for the points (1,1) & (10,10),
And there is a limit on the points the maximum point is (12,12).
my approach is to convert the above picture to an undirected graph with all weights to 1, and then find the shortest path.
here are my function that finds the shortest path:
int minCost;
vector<int> path;
multimap<int,int> Connections;
typedef multimap<int,int>::iterator mmit;
void shortestPath(int cs){
if(cs > minCost)
return;
if(path.back() == Target){
if(cs < minCost)
minCost = cs;
return;
}
pair<mmit,mmit> it = Connections.equal_range(path.back());
mmit mit = it.first;
for( ; mit != it.second ; ++mit){
if(isVisited(mit->second))
continue;
markVisited(mit->second);
path.push_back(mit->second);
shortestPath(cs+1);
markUnvisited(mit->second);
path.pop_back();
}
}
Is there any way faster than this ?? could i use dijkstra for this undirected graph ??
Using Dijkstra or any kind of graph-based search seems like total overkill here. At each vertex, you just need to choose the next vertex that brings you closer to your target.
So you start in the centre of (1,1). You need to choose the starting vertex. Obviously this is the one in the south-east.
From there, you have three choices: move west, move north-east or move south-east. This is in fact the choice you have at every second vertex. You choose the direction that brings you closer (ie, subtends smallest angle with your target).
In fact, you can represent all your vertex co-ordinates in a sort of cheaty way. Notice that they are all roughly half-way between the hexagon coordinates. So you could say the first vertex is at
(1.5,1.33).Your possible moves at the first co-ordinate are the directions:
Let’s call that the odd-movement. Now, the even-movement you have these choices:
So all you have to do is, for each possible direction, test the new distance (as the crow flies — ie pythagoras) to your target. Choose the new vertex that has the smallest distance of the three choices. Obviously you don’t have to compute the actual distance — distance squared is fine.
You can figure out the initial and final moves, I’m sure.
One final point, obviously I’m using double arithmetic which is imprecise. You can scale all your directions (and of course your hexagon co-ordinates) by 6 and use integers.