

- 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
Final cell position in the matrix in C++
Suppose we have a set of commands as a string, the string will have four different letters for four directions. U for up, D for down, L for left and R for right. We also have initial cell position (x, y). Find the final cell position of the object in the matrix after following the given commands. We will assume that the final cell position is present in the matrix. Suppose the command string is like “DDLRULL”, initial position is (3, 4). The final position is (1, 5).
The approach is simple, count the number of up, down, left and right movements, then find final position (x’, y’) using the formula −
(x’, y’) = (x + count_right – count_left,y + (count_down – count_up))
Example
#include<iostream> using namespace std; void getFinalPoint(string command, int x, int y) { int n = command.length(); int count_up, count_down, count_left, count_right; int x_final, y_final; count_up = count_down = count_left = count_right = 0; for (int i = 0; i < n; i++) { if (command[i] == 'U') count_up++; else if (command[i] == 'D') count_down++; else if (command[i] == 'L') count_left++; else if (command[i] == 'R') count_right++; } x_final = x + (count_right - count_left); y_final = y + (count_down - count_up); cout << "Final Position: " << "(" << x_final << ", " << y_final << ")"; } int main() { string command = "DDLRULL"; int x = 3, y = 4; getFinalPoint(command, x, y); }
Output
Final Position: (1, 5)
- Related Questions & Answers
- How to position component at the top of the grid cell with GridBagLayout in Java?
- Program to find next state of next cell matrix state in Python?
- Program to get final position of moving animals when they stops in Python
- C++ code to count steps to reach final position by robot
- C++ Program to check k rupees are enough to reach final cell or not
- Cell fusion in Python
- Working Principle of Voltaic Cell (Galvanic Cell)
- Explain final class and final method in PHP.
- Find paths from corner cell to middle cell in maze in C++
- Find the minimum number of moves needed to move from one cell of matrix to another in Python
- Explain the ATM Cell Structure in Computer Network
- Program to generate matrix where each cell holds Manhattan distance from nearest 0 in Python
- How to expand a matrix rows by their index position in R?
- Find sum of all elements in a matrix except the elements in row and-or column of given cell in Python
- final variables in Java
Advertisements