- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Robot Return to Origin in C++
Suppose there is a robot and its starting position is (0, 0). If we have a sequence of its movements, we have to check whether this robot ends up at (0, 0) after it completes its moves.
The move sequence is given as a string, and the character moves[i] represents its ith move. Symbols are R for right, L for left, U for up, and D for down. If the robot returns to the origin after it finishes all of its moves, return true. Otherwise, return false.
So, if the input is like "RRULLD", then the output will be true, Right two-unit, then go up, then left two unit then again down, so this is the starting position.
To solve this, we will follow these steps −
l := size of moves array
if l is same as 0, then −
return true
lft := 0, up := 0
for initialize i := 0, when i < l, update (increase i by 1), do −
if moves[i] is same as 'L', then −
(increase lft by 1)
if moves[i] is same as 'R', then −
(decrease lft by 1)
if moves[i] is same as 'U', then −
(increase up by 1)
if moves[i] is same as 'D', then −
(decrease up by 1)
if lft is same as 0 and up is same as 0, then −
return true
return false
Example
Let us see the following implementation to get a better understanding −
#include <bits/stdc++.h> using namespace std; class Solution { public: bool judgeCircle(string moves) { int l = moves.length(); if (l == 0) { return true; } int lft = 0, up = 0; for (int i = 0; i < l; i++) { if (moves[i] == 'L') { lft++; } if (moves[i] == 'R') { lft--; } if (moves[i] == 'U') { up++; } if (moves[i] == 'D') { up--; } } if (lft == 0 && up == 0) { return true; } return false; } }; main(){ Solution ob; cout << (ob.judgeCircle("RRULLD")); }
Input
"RRULLD"
Output
1
- Related Articles
- Robot Bounded In Circle C++
- Position of robot after given movements in C++
- Furthest From Origin in C++
- C++ code to find reduced direction string of robot movement
- C++ code to count steps to reach final position by robot
- Walking Robot Simulation in Python
- Find K Closest Points to the Origin in C++
- Finding points nearest to origin in JavaScript
- C++ Program to find out the total cost required for a robot to make a trip in a grid
- Program to check robot can reach target position or not in Python
- Check if a line passes through the origin in C++
- C++ program to find out the maximum number of cells a cleaning robot can clean in a grid
- Will the first robot in the bedroom be a "women"?
- C++ Program to find out the number of jumps needed for a robot to reach a particular cell in a grid
- How to “return an object” in C++?
