Given a string path, where path[i] ∈ {‘N’, ‘S’, ‘E’, ‘W’}, each character representing a move north, south, east, or west, respectively. Initially, you start at the origin (0, 0) on a 2D plane. Return true if the path crosses itself at any point; otherwise, return false.
#include <iostream>
#include <unordered_set>
#include <string>
bool isPathCrossing(std::string path) {
std::unordered_set<std::string> visited;
int x = 0, y = 0;
visited.insert("0,0");
for (char dir : path) {
if (dir == 'N') {
++y;
} else if (dir == 'S') {
--y;
} else if (dir == 'E') {
++x;
} else if (dir == 'W') {
--x;
} else {
// Invalid Input
return false;
}
std::string position = std::to_string(x) + "," + std::to_string(y);
if (visited.find(position) != visited.end()) {
return true;
}
visited.insert(position);
}
return false;
}
// Example usage
int main() {
std::string path1 = "NES";
std::string path2 = "NESWW";
std::cout << isPathCrossing(path1) << std::endl; // Output: false
std::cout << isPathCrossing(path2) << std::endl; // Output: true
return 0;
}
visited
to track all visited positions and initializes start position (0, 0)
.visited
set, returns true
.false
.Adjust the code and input handling if there are additional constraints or edge cases specified.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?