# Find single Movement in a Matrix in C++

C++Server Side ProgrammingProgramming

In this problem, we are given four values x1, y1, x2, y2 denoting two points (x1, y1) and (x2, y2). Our task is to find single movement in a Matrix. We need to find the direction using which we can move from one point (x1, y1) to (x2, y2). There can be any number of moves by the direction needed to be single and we need to return the direction in the form - “left” , “right”, “up”, “down”. Otherwise return -1, denoting “not possible”.

Let’s take an example to understand the problem,

## Input

x1 = 2, y1 = 1, x2 = 5, y1 = 1

## Output

Right

## Solution Approach

A simple solution to the problem is using the fact that to reach destination from source, either of the two coordinates x1:x2 or y1:y2 need to be the same. For the values, here are the cases −

Case 1: x1 = x2 & y1 > y2 -> Direction : Left
Case 1: x1 = x2 & y2 > y1 -> Direction : Right
Case 1: y1 = y2 & x1 > x2 -> Direction : Up
Case 1: y1 = y2 & x2 > x1 -> Direction : Down

Program to illustrate the working of our solution,

## Example

Live Demo

#include <iostream>
using namespace std;
void findSingleMovement(int x1, int y1, int x2, int y2) {
if (x1 == x2 && y1 < y2)
cout<<"Right";
else if (x1 == x2 && y1 > y2)
cout<<"Left";
else if (y1 == y2 && x1 < x2)
cout<<"Down";
else if (y1 == y2 && x1 > x2)
cout<<"Up";
else
cout<<"Not Possible";
}
int main() {
int x1, x2, y1, y2;
x1 = 2; y1 = 1;
x2 = 5; y2 = 1;
cout<<"The direction of movement is ";
findSingleMovement(x1, y1, x2, y2);
return 0;
}

## Output

The direction of movement is Down
Published on 16-Mar-2021 06:27:36