[알고리즘/C#] 프로그래머스 - 당구 연습 (점과 점 사이 거리, 대칭이동 좌표)

0시0분·2024년 8월 14일
0

알고리즘

목록 보기
13/23

🖋️ 풀이 방법
생각보다는 단순하게 풀었다.
입사각과 반사각이 동일하다고 했기 때문에 그냥 공을 대칭시켜서 일직선으로 만들고,
두 점 사이의 거리를 구한다.
예외사항으로는 칠 공과 대칭축 사이에 맞춰야 할 공이 있는 경우만 조심하면 된다.
이 경우에는 원쿠션이 아니다.

using System;

public class Solution {
    public int CalcDist(int x1, int x2, int y1, int y2)
    {
        return  (x2-x1) * (x2-x1) + (y2-y1) * (y2-y1);
    }

    public int[] solution(int m, int n, int startX, int startY, int[,] balls) 
    {
        int[] answer = new int[balls.GetLength(0)];

        for (int i = 0; i < balls.GetLength(0); ++i)
        {
            int newX, newY;
            int minDist = int.MaxValue;

            int destX = balls[i, 0];
            int destY = balls[i, 1];

            bool cannotRightFlip = destY == startY && startX < destX;
            bool cannotLeftFlip = destY == startY && startX > destX;
            bool cannotUpFlip = destX == startX && destY > startY;
            bool cannotDownFlip = destX == startX && destY < startY;

            if (cannotRightFlip == false)
            {
                newX = 2 * m - startX;
                minDist = Math.Min(minDist, CalcDist(newX, destX, startY, destY));
            }

            if (cannotLeftFlip == false)
            {
                newX = -startX;
                minDist = Math.Min(minDist, CalcDist(newX, destX, startY, destY));
            }

            if (cannotUpFlip == false)
            {
                newY = 2 * n - startY;
                minDist = Math.Min(minDist, CalcDist(startX, destX, newY, destY));
            }

            if (cannotDownFlip == false)
            {
                newY = -startY;
                minDist = Math.Min(minDist, CalcDist(startX, destX, newY, destY));
            }

            answer[i] = minDist;
        }

        return answer;
    }
}

🤔 아쉬운 점
점과 점 사이 거리, 점과 직선사이 거리 등은 자주 쓰이는건데도 매번 헷갈린다..
특히 이번엔 대칭을 사용해서 풀었기 때문에 대칭이동 공식도 따로 찾아봐야 했다. 😔


📝

0개의 댓글