
- C++ Basics
- C++ Home
- C++ Overview
- C++ Environment Setup
- C++ Basic Syntax
- C++ Comments
- C++ Data Types
- C++ Variable Types
- C++ Variable Scope
- C++ Constants/Literals
- C++ Modifier Types
- C++ Storage Classes
- C++ Operators
- C++ Loop Types
- C++ Decision Making
- C++ Functions
- C++ Numbers
- C++ Arrays
- C++ Strings
- C++ Pointers
- C++ References
- C++ Date & Time
- C++ Basic Input/Output
- C++ Data Structures
- C++ Object Oriented
- C++ Classes & Objects
- C++ Inheritance
- C++ Overloading
- C++ Polymorphism
- C++ Abstraction
- C++ Encapsulation
- C++ Interfaces
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 Articles
- Who gave the final shape to cell theory?
- Program to get final position of moving animals when they stops in Python
- Add text and number into specified position of cell in Excel
- How to position component at the top of the grid cell with GridBagLayout in Java?
- C++ code to count steps to reach final position by robot
- Program to find next state of next cell matrix state in Python?
- Draw in your notebook the symbol store present the following components of electrical circuits: connecting wires, switch in the ‘OFF’ position, bulb, cell, switch in the ‘ON’ position, and battery.
- How to expand a matrix rows by their index position in R?
- Explain final class and final method in PHP.
- C++ Program to check k rupees are enough to reach final cell or not
- final keyword in Java
- Final variable in Java
- Final class in Java
- Final Arrays in Java
- final variables in Java

Advertisements