
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
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)
Advertisements