KimMinJun
Coding Note
KimMinJun
전체 방문자
오늘
어제
  • 분류 전체보기 (505) N
    • CS (1)
    • Web (27) N
      • Vanilla JS (13)
      • TS (2)
      • React (7)
      • Next.js (3) N
      • ETC (1)
    • Docker (14)
    • Git (5)
    • ALGORITHM (11)
      • 정렬 (6)
      • 최단경로 (1)
      • 자료구조 (1)
      • 슬라이딩 윈도우 (1)
      • etc (2)
    • PS (432)
      • 백준 (187)
      • Programmers (105)
      • CodeUp (21)
      • STL (3)
      • 제코베 JS 100제 (50)
      • SWEA (0)
      • LeetCode (65)
    • IT (1)
    • React 공식문서 (번역, 공부) (11)
      • Quick Start (2)
      • Installation (0)
      • Describing the UI (9)
      • Adding Interactivity (0)
      • Managing State (0)
      • Escape Hatches (0)
    • Next.js 공식문서 (번역, 공부) (3)
      • Getting Started (2)
      • Building Your Application (1)

블로그 메뉴

  • 홈
  • 태그
  • 방명록
  • 관리

공지사항

인기 글

태그

  • 그래프
  • recursion
  • 수학
  • codeup
  • tree
  • js
  • programmers
  • Level 1
  • 제코베 JS 100제
  • 백준
  • 정렬
  • Level 2
  • 다이나믹 프로그래밍
  • Level1
  • Level 0
  • C++
  • C
  • LeetCode
  • 문자열
  • string

최근 댓글

최근 글

hELLO · Designed By 정상우.
KimMinJun

Coding Note

PS/LeetCode

LeetCode / Graph / 994번 / Rotting Oranges / JS

2023. 4. 29. 18:05

< 문제 바로가기 >

 

Rotting Oranges - LeetCode

Can you solve this real interview question? Rotting Oranges - You are given an m x n grid where each cell can have one of three values: * 0 representing an empty cell, * 1 representing a fresh orange, or * 2 representing a rotten orange. Every minute, any

leetcode.com

 

< 문제 간단설명 >

m * n의 격자판이 주어지는데 다음과 같은 각 셀은 3가지 상태중 하나를 가진다

  • 0: 빈 셀
  • 1: 신선한 오렌지가 있는 셀
  • 2: 썩은 오렌지가 있는 셀

매 분, 상하좌우로 썩은 오렌지는 신선한 오렌지를 썩게 만든다.

남은 신선한 오렌지가 없을 때, 총 몇분이 걸렸는지 반환하는 문제이다.

 

만약 불가능하다면 -1을 반환하면 된다.

 

/**
 * @param {number[][]} grid
 * @return {number}
 */
var orangesRotting = function (grid) {
  const [GRID_ROW, GRID_COL] = [grid.length, grid[0].length];
  const DIR_OBJ = {
    UP: [-1, 0],
    DOWN: [1, 0],
    LEFT: [0, -1],
    RIGHT: [0, 1],
  };

  let queue = [];

  let freshOrangeCount = 0;
  let cur = -1;
  for (let i = 0; i < GRID_ROW; i += 1) {
    for (let j = 0; j < GRID_COL; j += 1) {
      cur = grid[i][j];

      // 신선한 오렌지일 경우
      if (cur === 1) {
        freshOrangeCount += 1;
      }
      // 썩은 오렌지일 경우
      else if (cur === 2) {
        queue.push([i, j]);
      }
    }
  }

  const isValidIndex = (row, col) => {
    // grid의 최대 행을 넘어갈 때
    if (row < 0 || row >= GRID_ROW) {
      return false;
    }
    // grid의 최대 열을 넘어갈 때
    if (col < 0 || col >= GRID_COL) {
      return false;
    }

    return true;
  };

  // 처음부터 신선한 오렌지가 없을 경우
  if (freshOrangeCount === 0) {
    return 0;
  }

  let minutes = 0;
  while (queue.length) {
    let len = queue.length;
    for (let i = 0; i < len; i += 1) {
      const [ROTTING_ROW, ROTTING_COL] = queue.shift();

      for (const [MOVE_ROW, MOVE_COL] of Object.values(DIR_OBJ)) {
        const NEXT_ROW = ROTTING_ROW + MOVE_ROW;
        const NEXT_COL = ROTTING_COL + MOVE_COL;

        // grid의 최대 인덱스 초과
        if (isValidIndex(NEXT_ROW, NEXT_COL) === false) {
          continue;
        }
        // 빈 공간
        if (grid[NEXT_ROW][NEXT_COL] !== 1) {
          continue;
        }

        queue.push([NEXT_ROW, NEXT_COL]);
        // 썩은 상태로 바꿔줌
        grid[NEXT_ROW][NEXT_COL] = 2;
        // 신선한 오렌지 개수 - 1
        freshOrangeCount -= 1;
      }
    }

    // 만약 큐에 담긴 다음칸들을 모두 갈 수 있다면
    if (queue.length > 0) {
      minutes += 1;
    }

    // 남은 신선한 오렌지가 없을 경우
    if (freshOrangeCount === 0) {
      return minutes;
    }
  }

  return -1;
};
저작자표시 (새창열림)

'PS > LeetCode' 카테고리의 다른 글

LeetCode / Graph / 210번 / Course Schedule II / JS  (0) 2023.05.14
LeetCode / Graph / 417번 / Pacific Atlantic Water Flow / JS  (0) 2023.04.29
LeetCode / Binary Search Tree / 173번 / Binary Search Tree Iterator / JS  (0) 2023.04.29
LeetCode / Binary Search Tree / 230번 / Kth Smallest Element in a BST / JS  (0) 2023.04.29
    'PS/LeetCode' 카테고리의 다른 글
    • LeetCode / Graph / 210번 / Course Schedule II / JS
    • LeetCode / Graph / 417번 / Pacific Atlantic Water Flow / JS
    • LeetCode / Binary Search Tree / 173번 / Binary Search Tree Iterator / JS
    • LeetCode / Binary Search Tree / 230번 / Kth Smallest Element in a BST / JS
    KimMinJun
    KimMinJun

    티스토리툴바