[LeetCode] Path Crossing

1496. Path Crossing

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class Solution {
public:
bool isPathCrossing(string path) {
set<pair<int,int>> st;
int x = 0, y = 0;
auto move = [&](char p) {
if(p == 'N') y += 1;
else if(p == 'S') y -= 1;
else if(p == 'E') x += 1;
else if(p == 'W') x -= 1;
};
auto ok = [&]() {
if(st.count({x,y})) return true;
st.insert({x,y});
return false;
};
ok();
for(auto& p : path) {
move(p);
if(ok()) return true;
}
return false;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2023/12/23/PS/LeetCode/path-crossing/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.