주녘공부일지

[프로그래머스 C#] Lv.1 공원 산책 본문

Programmers - C#/CodingTest Lv.1

[프로그래머스 C#] Lv.1 공원 산책

주녘 2023. 8. 18. 17:02
728x90

https://school.programmers.co.kr/learn/courses/30/lessons/172928

 

프로그래머스

코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.

programmers.co.kr

1. 정답코드 및 핵심 아이디어, 유의사항

- currPosition이라는 현재 위치를 가진 int형 배열을 선언

 

주석 참조

    using System;

    public class Solution
    {
        public int[] solution(string[] park, string[] routes)
        {
            int[] currPosition = new int[2] { -1, -1 };

            // 출발 위치 찾기
            for (int i = 0; i < park.Length; i++)
            {
                for (int j = 0; j < park[i].Length; j++)
                {
                    if (park[i][j] == 'S')
                    {
                        currPosition[0] = i;
                        currPosition[1] = j;
                        break;
                    }
                }
                if (currPosition[0] != -1 && currPosition[1] != -1)
                    break;
            }

            // 길 찾기
            for (int i = 0; i < routes.Length; i++)
            {
                int moveToY, moveToX;
                moveToY = currPosition[0];
                moveToX = currPosition[1];
                bool isMove = true;

                for (int j = 0; j < (int)routes[i][2] - (int)'0'; ++j)
                {
                    if (routes[i][0] == 'N') moveToY--;
                    else if (routes[i][0] == 'S') moveToY++;
                    else if (routes[i][0] == 'E') moveToX++;
                    else if (routes[i][0] == 'W') moveToX--;

                    if (moveToY < 0 || moveToY >= park.Length ||
                        moveToX < 0 || moveToX >= park[0].Length ||
                        park[moveToY][moveToX] == 'X')
                    {
                        isMove = false;
                        break;
                    }
                }

                if (isMove)
                    currPosition = new int[2] { moveToY, moveToX };
            }

            return currPosition;
        }
    }
728x90