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.
Input: path = "NES"
Output: false
Explanation: Notice that the path doesn't cross any point more than once.
Input: path = "NESWW"
Output: true
Explanation: Notice that the path visits the origin twice.
/**
* @param {string} path
* @return {boolean}
*/
var isPathCrossing = function(path) {
let tmp = [];
/* 좌표들 */
let x = 0;
let y = 0;
for (let i = 0; i < path.length; i++) {
tmp.push([x, y])
switch (path[i]) {
case "N":
y++
break;
case "W":
x--
break;
case "E":
x++
break;
case "S":
y--
break;
}
/* x, y좌표중 겹치는 게 있나 임시 배열로 확인 */
for (let j = 0; j < tmp.length; j++) {
if (tmp[j][0] == x && tmp[j][1] == y) {
return true;
}
}
}
return false;
};