[Solved] Shortest path on 4×4 grid c++


As you have already pointed out yourself in the comments, the shortest path from (0,2) to (3,1) is “right 3 down 1” in other words: right 3-0=3 and down 2-1=1

And that’s already pretty much the answer…

In general, how do find the shortest path from (xStart, yStart) to (xEnd, yEnd)? You just do the same thing as before again. It is “right xEnd-xStart, down yEnd-yStart”.

So everything that the print_path function requires is just “where do I start” and “how much do I go right/left and how much do I go up/down?”

So you could use two variable in create_path

int right = xEnd-xStart;
int down = yEnd-yStart;

and you send these to print_path. You have not provided the signature of print_path, but it could look like this:

void print_path(int xStart, int yStart, int right, int down) 
{

}

Within this function you just do two loops:

int i = xStart;
int xend = xStart + right; // observe: if right is negative, it's just subtraction
bool right = (right >= 0); // are we going right or left?

while(i != xend) {
     std::cout << "next waypoint: x = " << i << ", y = " << yStart << std::endl;
     if (right) {
          i++;
     } else {
          i--;
     }
}

And now you do the same thing for the y coordinate

int j = yStart;
int yend = yStart + down; 
bool down = (down >= 0); // are we going down or up?

while(j != yend) {
     std::cout << "next waypoint: x = " << xend << ", y = " << j << std::endl;
     if (down) {
          j++;
     } else {
          j--;
     }
}

2

solved Shortest path on 4×4 grid c++