Minimum number of stops from given path in C++

C++Server Side ProgrammingProgramming

Problem statement

  • There are many points in two-dimensional space which need to be visited in a specific sequence.
  • Path from one point to other is always chosen as shortest path and path segments are always aligned with grid lines.
  • We are given the path which is chosen for visiting the points. We need to tell the minimum number of points that must be needed to generate given paths.


1. We can solve this problem by observing the pattern of movement when visiting the stop
2. If we want to take the shortest path from one point to another point, then we will move in either one or max two directions


 Live Demo

#include <bits/stdc++.h>
using namespace std;
int getMinStops(string path) {
   int n = path.length();
   map<char, int> directionMap;
   int stops = 1;
   for (int i = 0; i < n; ++i) {
      char direction = path[i];
      directionMap[direction] = 1;
      if ((directionMap['L'] && directionMap['R']) ||
      (directionMap['U'] && directionMap['D'])) {
         directionMap[direction] = 1;
   return stops + 1;
int main() {
   string path = "LLUUULLDD";
   cout << "Minimum stops = " << getMinStops(path) << endl;
   return 0;

When you compile and execute above program. It generates following output


Minimum stops = 3
Published on 23-Dec-2019 06:20:19