๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
๐Ÿง  ์•Œ๊ณ ๋ฆฌ์ฆ˜

[ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค] ๋‹น๊ตฌ ์—ฐ์Šต JS

by megan07 2024. 1. 3.

๋ฌธ์ œ ๋งํฌ

ํ’€์ด

์ด ๋ฌธ์ œ๋„ ์ƒ๊ฐ๋ณด๋‹ค ์˜ค๋ž˜ ๊ฑธ๋ ธ์Šต๋‹ˆ๋‹ค
์ฒ˜์Œ์—๋Š” (์‹œ์ž‘๊ณต๊ณผ ๋ฒฝ๋ฉด์˜ ๊ฑฐ๋ฆฌ + ๋ฒฝ๋ฉด๊ณผ ๋„์ฐฉ๊ณต์˜ ๊ฑฐ๋ฆฌ)์˜ ์ œ๊ณฑ์„ ๊ตฌํ–ˆ๋Š”๋ฐ 

๊ฐ ๊ฑฐ๋ฆฌ๋ฅผ ๊ตฌํ•˜๋Š” ๊ณผ์ •์—์„œ ์‹ค์ˆ˜๊ฐ€ ๋‚˜์™€์„œ ์˜ค์ฐจ๊ฐ€ ์ƒ๊ธฐ๋”๋ผ๊ตฌ์š”


๋‹ค๋ฅธ ๋ถ„๋“ค์˜ ํ’€์ด๋ฅผ ์ฐพ์•„๋ณด๋‹ˆ ์ ์„ ๋Œ€์นญ์‹œ์ผœ์„œ ๊ตฌํ•˜๋Š”๊ฑฐ์˜€์Šต๋‹ˆ๋‹ค

 

๋„์ฐฉ๊ณต์˜ ์ขŒํ‘œ๋ฅผ ์ƒ[0], ํ•˜[1], ์ขŒ[2], ์šฐ[3] ๋Œ€์นญ์‹œํ‚ด
๋Œ€์นญ์‹œํ‚จ ๋„์ฐฉ๊ณต์˜ ์ขŒํ‘œ์™€ ์‹œ์ž‘๊ณต ์‚ฌ์ด์˜ ๊ฑฐ๋ฆฌ๋ฅผ ๊ตฌํ•จ
๋Œ€์‹  ์‹œ์ž‘๊ณต์ด ๋ฒฝ๋ณด๋‹ค ๋„์ฐฉ๊ณต์„ ๋จผ์ € ๋งŒ๋‚˜๋Š” ์ƒํ™ฉ์ด๋ฉด ๊ฑด๋„ˆ๋›ด๋‹ค

์˜ˆ๋ฅผ ๋“ค์–ด
๋„์ฐฉ๊ณต์„ ์œ„์ชฝ์œผ๋กœ ๋Œ€์นญ์‹œํ‚ฌ๊ฑด๋ฐ(์‹œ์ž‘๊ณต์„ ์ƒ๋‹จ๋ฒฝ์— ๋ถ€๋”ชํžˆ๊ฒŒ ๋งŒ๋“ค๊ณ ) &&
๋‘ ๊ณต์ด ๊ฐ™์€ ์„ธ๋กœ์„ ์ƒ์— ์žˆ๊ณ  &&
์‹œ์ž‘๊ณต์ด ๋„์ฐฉ๊ณต ์•„๋ž˜์ชฝ์— ์žˆ๋‹ค๋ฉด
=> ๋ฒฝ์— ๋ถ€๋”ชํžˆ๊ธฐ ์ „์— ๋„์ฐฉ๊ณต์— ๋ถ€๋”ชํžˆ๋ฏ€๋กœ continue;

์ดํ•ด๊ฐ€ ์•ˆ๊ฐ€์‹œ๋Š” ๋ถ„๋“ค์€ ์•„๋ž˜ ๋งํฌ ์ฐธ๊ณ ํ•ด์ฃผ์„ธ์š”!!

https://silverstonec.tistory.com/56

function solution(m, n, startX, startY, balls) {
  const answer = [];

  for (const [endX, endY] of balls) {
    let min = Infinity;

    //end๋ฅผ ์ƒ[0], ํ•˜[1], ์ขŒ[2], ์šฐ[3] ๋Œ€์นญ
    const symmetryX = [endX, endX, -endX, m + m - endX];
    const symmetryY = [n + n - endY, -endY, endY, endY];

    for (let i = 0; i < 4; i++) {
      //์‹œ์ž‘๊ณต์ด ๋ฒฝ๋ณด๋‹ค ๋„์ฐฉ๊ณต์„ ๋จผ์ € ๋งŒ๋‚˜๋Š” ์ƒํ™ฉ์ด๋ฉด ๊ฑด๋„ˆ๋›ด๋‹ค

      //๋„์ฐฉ๊ณต์„ ์œ„์ชฝ์œผ๋กœ ๋Œ€์นญ์‹œํ‚ฌ๊ฑด๋ฐ(์‹œ์ž‘๊ณต์„ ์ƒ๋‹จ๋ฒฝ์— ๋ถ€๋”ชํžˆ๊ฒŒ ๋งŒ๋“ค๊ฑด๋ฐ) &&
      //๋‘ ๊ณต์ด ๊ฐ™์€ ์„ธ๋กœ์„ ์ƒ์— ์žˆ๊ณ  &&
      //์‹œ์ž‘๊ณต์ด ๋„์ฐฉ๊ณต ์•„๋ž˜์ชฝ์— ์žˆ๋‹ค๋ฉด
      //=> ๋ฒฝ์— ๋ถ€๋”ชํžˆ๊ธฐ ์ „์— ๋„์ฐฉ๊ณต์— ๋ถ€๋”ชํžˆ๋ฏ€๋กœ continue;
      if (i === 0 && startX === endX && startY < endY) continue;
      //๋‚˜๋จธ์ง€ 3๊ฐœ๋„ ์ด๋Ÿฐ ์‹์œผ๋กœ ์‹œ์ž‘๊ณต์ด ์•„๋ž˜, ์™ผ์ชฝ, ์˜ค๋ฅธ์ชฝ ๋ฒฝ๋ฉด์— ๋จผ์ € ๋ถ€๋”งํžˆ์ง€ ๋ชปํ•˜๋Š” ๊ฒฝ์šฐ
      if (i === 1 && startX === endX && startY > endY) continue;
      if (i === 2 && startY === endY && startX > endX) continue;
      if (i === 3 && startY === endY && startX < endX) continue;

      //๋Œ€์นญ์‹œํ‚จ ๋„์ฐฉ๊ณต์˜ ์ขŒํ‘œ์™€ ์‹œ์ž‘๊ณต ์‚ฌ์ด์˜ ๊ฑฐ๋ฆฌ๋ฅผ ๊ตฌํ•จ
      const length =
        (startX - symmetryX[i]) ** 2 + (startY - symmetryY[i]) ** 2;
      min = Math.min(min, length);
    }

    answer.push(min);
  }

  return answer;
}