# Check if it is possible to return to the starting position after moving in the given directions in C++

C++Server Side ProgrammingProgramming

Suppose we are at position (0, 0) We have a string represents consecutive directions using four letters. We have to check whether we can return at (0, 0) position after considering all of the given directions. The symbols are

• E for east
• W for west
• N for north
• S for south.

So, if the input is like "EENWWS", then the output will be true, move east two units, then go north, then west two units then again south, 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 'W', then −
• (increase lft by 1)
• if moves[i] is same as 'E', then −
• (decrease lft by 1)
• if moves[i] is same as 'N', then −
• (increase up by 1)
• if moves[i] is same as 'S', then:
• (decrease up by 1)
• if lft is same as 0 and up is same as 0, then −
• return true
• return false

## Example (C++)

Let us see the following implementation to get better understanding −

Live Demo

#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
bool solve(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] == 'W') {
lft++;
}
if (moves[i] == 'E') {
lft--;
}
if (moves[i] == 'N') {
up++;
}
if (moves[i] == 'S') {
up--;
}
}
if (lft == 0 && up == 0) {
return true;
}
return false;
}
};
}
main(){
Solution ob;
cout << (ob.solve("EENWWS"));
}

## Input

"EENWWS"

## Output

1