코딩공부/프로그래머스

※[프로그래머스]Lv.2 방문 길이C# (양방향 비교하기)

usingsystem 2023. 7. 28. 17:22
728x90

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

 

프로그래머스

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

programmers.co.kr

소스코드

문제에 함정이있었다 처음에 2차배열로 풀었지만 양방향으로 비교를 했다.

using System;
using System.Collections.Generic;
public class Solution
{
    public int solution(string dirs)
    {
        int answer = 0;

        bool[,,,] visit = new bool[11, 11, 11, 11];

        Queue<Pos> q = new Queue<Pos>();
        q.Enqueue(new Pos(5, 5));
        visit[5, 5, 5, 5] = true;

        for (int i = 0; i < dirs.Length; i++)
        {
            Pos now = q.Dequeue();
            int nextY = now.PosY;
            int nextX = now.PosX;

            switch (dirs[i])
            {
                case 'U':
                    nextY--;
                    break;
                case 'D':
                    nextY++;
                    break;
                case 'R':
                    nextX++;
                    break;
                case 'L':
                    nextX--;
                    break;
            }

            if (nextY < 0 || nextY > 10 || nextX < 0 || nextX > 10)
            {
                q.Enqueue(now);
                continue;
            }

            if (visit[nextY, nextX, now.PosY, now.PosX] == true || visit[now.PosY, now.PosX, nextY, nextX] == true)
            {
                q.Enqueue(new Pos(nextY, nextX));
                continue;
            }
            visit[now.PosY, now.PosX, nextY, nextX] = true;
            visit[nextY, nextX, now.PosY, now.PosX] = true;

            answer++;
            q.Enqueue(new Pos(nextY, nextX));
        }

        return answer;
    }
}
class Pos
{
    public int PosY;
    public int PosX;

    public Pos(int y, int x)
    {
        PosY = y;
        PosX = x;
    }
}
728x90