1496. Path Crossing

동청·2022년 11월 2일
0

leetcode

목록 보기
29/39

Problem

leetcode 바로가기

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.

Example 1:

Input: path = "NES"
Output: false 
Explanation: Notice that the path doesn't cross any point more than once.

Example 2:

Input: path = "NESWW"
Output: true
Explanation: Notice that the path visits the origin twice.

Constraints:

  • 1 <= path.length <= 104^4
  • path[i] is either 'N', 'S', 'E', or 'W'.

Solution

/**
 * @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;
};

0개의 댓글