

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Minimum number of stops from given path in C++
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.
Algorithm
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
Example
#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.clear(); ++stops; 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
Output
Minimum stops = 3
- Related Questions & Answers
- Minimum Number of Refueling Stops in C++
- Program to find minimum number of busses are required to pass through all stops in Python
- Minimum number using set bits of a given number in C++
- Minimum Path Sum in C++
- Minimum Path Sum in Python
- Minimum number of squares whose sum equals to given number n
- Minimum number of coins that make a given value
- Longest consecutive path from a given starting character
- Minimum Falling Path Sum in C++
- Convert a number m to n using minimum number of given operations in C++
- C Program for Minimum Cost Path
- Path With Maximum Minimum Value in Python
- Minimum Falling Path Sum II in C++
- Find length of the longest consecutive path from a given starting characters in C++
- Minimum Sum Path in a Triangle in C++
Advertisements