Minimum number of stops from given path
Last Updated :
02 Mar, 2023
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. Now 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 path. Examples:
In above diagram, we can see that there
must be at least 3 points to get above
path, which are denoted by A, B and C
We can solve this problem by observing the pattern of movement when visiting the stops. 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 i.e. it is always possible to reach the other point following maximum two directions and if more than two directions are used then that path won’t be shortest, for example, path LLURD can be replaced with LLL only, so to find minimum number of stops in the path, we will loop over the characters of the path and maintain a map of directions taken till now.
If at any index we found both ‘L’ as well as ‘R’ or we found both ‘U’ as well as ‘D’ then there must be a stop at current index, so we will increase the stop count by one and we will clear the map for next segment. Total time complexity of the solution will be O(N)
Implementation:
CPP
// C++ program to find minimum number of points
// in a given path
#include <bits/stdc++.h>
using namespace std;
// method returns minimum number of points in given path
int numberOfPointInPath(string path)
{
int N = path.length();
// Map to store last occurrence of direction
map<char, int> dirMap;
// variable to store count of points till now,
// initializing from 1 to count first point
int points = 1;
// looping over all characters of path string
for (int i = 0; i < N; i++) {
// storing current direction in curDir
// variable
char curDir = path[i];
// marking current direction as visited
dirMap[curDir] = 1;
// if at current index, we found both 'L'
// and 'R' or 'U' and 'D' then current
// index must be a point
if ((dirMap['L'] && dirMap['R']) ||
(dirMap['U'] && dirMap['D'])) {
// clearing the map for next segment
dirMap.clear();
// increasing point count
points++;
// revisiting current direction for next segment
dirMap[curDir] = 1;
}
}
// +1 to count the last point also
return (points + 1);
}
// Driver code to test above methods
int main()
{
string path = "LLUUULLDD";
cout << numberOfPointInPath(path) << endl;
return 0;
}
Java
// Java program to find minimum number of points
// in a given path
import java.util.*;
public class GFG
{
// method returns minimum number of points in given path
public static int numberOfPointInPath(String path)
{
int N = path.length();
// Map to store last occurrence of direction
TreeMap<Character, Integer> dirMap
= new TreeMap<Character, Integer>();
// variable to store count of points till now,
// initializing from 1 to count first point
int points = 1;
dirMap.put('L', 0);
dirMap.put('R', 0);
dirMap.put('D', 0);
dirMap.put('U', 0);
// looping over all characters of path string
for (int i = 0; i < N; i++) {
// storing current direction in curDir
// variable
char curDir = path.charAt(i);
// marking current direction as visited
dirMap.put(curDir, 1);
// if at current index, we found both 'L'
// and 'R' or 'U' and 'D' then current
// index must be a point
if ((dirMap.get('L') == 1
&& dirMap.get('R') == 1)
|| (dirMap.get('U') == 1
&& dirMap.get('D') == 1)) {
// clearing the map for next segment
dirMap.put('L', 0);
dirMap.put('R', 0);
dirMap.put('D', 0);
dirMap.put('U', 0);
// increasing point count
points++;
// revisiting current direction for next
// segment
dirMap.put(curDir, 1);
}
}
// +1 to count the last point also
return (points + 1);
}
// Driver code to test above methods
public static void main(String[] args)
{
String path = "LLUUULLDD";
System.out.print(numberOfPointInPath(path));
System.out.print("\n");
}
}
// This code is contributed by Aarti_Rathi
Python3
# Python code implementation
# method returns minimum number of points in given path
def numberOfPointInPath(path):
N = len(path)
# Map to store last occurrence of direction
dirMap = {}
# variable to store count of points till now,
# initializing from 1 to count first point
points = 1
# looping over all characters of path string
for i in range(N):
# storing current direction in curDir
# variable
curDir = path[i]
# marking current direction as visited
dirMap[curDir] = 1
# if at current index, we found both 'L'
# and 'R' or 'U' and 'D' then current
# index must be a point
if ('L' in dirMap and 'R' in dirMap) or ('U' in dirMap and 'D' in dirMap):
dirMap.clear()
# increasing point count
points = points + 1
# revisiting current direction for next segment
dirMap[curDir] = 1
# +1 to count the last point also
return points + 1
# Test
path = "LLUUULLDD"
print(numberOfPointInPath(path))
# The code is contributed by Nidhi goel.
C#
using System;
using System.Collections.Generic;
public class GFG
{
public static int NumberOfPointInPath(string path)
{
int N = path.Length;
// Dictionary to store last occurrence of direction
Dictionary<char, int> dirMap = new Dictionary<char, int>();
dirMap['L'] = 0;
dirMap['R'] = 0;
dirMap['D'] = 0;
dirMap['U'] = 0;
// variable to store count of points till now,
// initializing from 1 to count first point
int points = 1;
// looping over all characters of path string
for (int i = 0; i < N; i++)
{
// storing current direction in curDir variable
char curDir = path[i];
// marking current direction as visited
dirMap[curDir] = 1;
// if at current index, we found both 'L' and 'R'
// or 'U' and 'D' then current index must be a point
if ((dirMap['L'] == 1 && dirMap['R'] == 1)
|| (dirMap['U'] == 1 && dirMap['D'] == 1))
{
// clearing the dictionary for next segment
dirMap['L'] = 0;
dirMap['R'] = 0;
dirMap['D'] = 0;
dirMap['U'] = 0;
// increasing point count
points++;
// revisiting current direction for next segment
dirMap[curDir] = 1;
}
}
// +1 to count the last point also
return (points + 1);
}
// Driver code to test above methods
public static void Main()
{
string path = "LLUUULLDD";
Console.Write(NumberOfPointInPath(path));
Console.Write("\n");
}
}
JavaScript
<script>
// method returns minimum number of points in given path
function numberOfPointInPath(path) {
let N = path.length;
// Map to store last occurrence of direction
let dirMap = new Map();
// variable to store count of points till now,
// initializing from 1 to count first point
let points = 1;
// looping over all characters of path string
for (let i = 0; i < N; i++) {
// storing current direction in curDir
// variable
let curDir = path[i];
// marking current direction as visited
dirMap.set(curDir, 1);
// if at current index, we found both 'L'
// and 'R' or 'U' and 'D' then current
// index must be a point
if ((dirMap.has('L') && dirMap.has('R')) || (dirMap.has('U') && dirMap.has('D'))) {
// clearing the map for next segment
dirMap.clear();
// increasing point count
points++;
// revisiting current direction for next segment
dirMap.set(curDir, 1);
}
}
// +1 to count the last point also
return points + 1;
}
// Test
let path = "LLUUULLDD";
console.log(numberOfPointInPath(path));
</script>
Time Complexity: O(n*logn).
Auxiliary Space: O(n)
Similar Reads
Minimum number of steps required to reach origin from a given point Given two integers A and B representing coordinates of a point in the first quadrant, the task is to find the minimum number of steps required to reach the origin. All possible moves from a point (i, j) are (i - 1, j), (i, j - 1) or (i, j) (staying at the same position). Note: It is not allowed to m
6 min read
Minimum number of items to be delivered Given N buckets, each containing A[i] items. Given K tours within which all of the items are needed to be delivered. It is allowed to take items from only one bucket in 1 tour. The task is to tell the minimum number of items needed to be delivered per tour so that all of the items can be delivered w
14 min read
Minimum number of lines needed to cross to reach at origin Given N number of integers in sorted format, where each integer Ai for all(1 ? i ? N), denotes the join of two points (0, Ai) and (Ai, 0) and forms a line by joining these two points, also given Q number of coordinates in form of (X, Y) in the first Quadrant. Return the minimum number of lines neede
15+ min read
Minimum number of operations required to return to the main folder Given an array of strings arr[] representing the changed folder operations(Unix-style) performed on the file system. Initially, the file system opens in the main folder. The task is to find the minimum count of operations of the following three types to return to the main folder: "../": Moves to the
6 min read
Number of minimum length paths between 1 to N including each node Given an undirected and unweighted graph of N nodes and M edges, the task is to count the minimum length paths between node 1 to N through each of the nodes. If there is doesn't exist any such path, then print "-1". Note: The path can pass through a node any number of times. Examples: Input: N = 4,
12 min read