Skip to content

1496. Path Crossing 👍

  • Time:
  • Space:
 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
class Solution {
 public:
  bool isPathCrossing(string path) {
    set<int> seen;

    seen.insert(0);

    int x = 0;
    int y = 0;

    for (const char c : path) {
      switch (c) {
        case 'N':
          ++y;
          break;
        case 'S':
          --y;
          break;
        case 'E':
          ++x;
          break;
        case 'W':
          --x;
          break;
      }
      const int key = x * 20001 + y;
      if (seen.contains(key))
        return true;
      seen.insert(key);
    }

    return false;
  }
};