
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
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
Advertisements