-
Notifications
You must be signed in to change notification settings - Fork 30
/
Copy pathPath Crossing.cpp
42 lines (32 loc) · 1.05 KB
/
Path Crossing.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
/*
Solution by Rahul Surana
***********************************************************
Given a string path, where path[i] = 'N', 'S', 'E' or 'W', each representing moving one unit
north, south, east, or west, respectively.
You start at the origin (0, 0) on a 2D plane and walk on the path specified by path.
Return true if the path crosses itself at any point, that is,
if at any time you are on a location you have previously visited. Return false otherwise.
***********************************************************
*/
class Solution {
public:
bool isPathCrossing(string path) {
set<pair<int,int>> s;
int x = 0, y = 0;
for(auto &q: path){
s.insert({x,y});
if(q == 'N'){
y++;
}
else if(q == 'S'){
y--;
}
else if(q == 'E'){
x++;
}
else x--;
if(s.count({x,y})) return true;
}
return false;
}
};