코딩공부/프로그래머스

[프로그래머스]Lv.2 무인도 여행 C#(BFS)

usingsystem 2023. 7. 4. 12:41
728x90

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

 

프로그래머스

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

programmers.co.kr

소스코드

using System;
using System.Collections.Generic;
public class Solution
{
    bool[,] found;
    public int[] solution(string[] maps)
    {
        found = new bool[maps.Length, maps[0].Length];
        List<int> answer = new List<int>();

        for (int i = 0; i < maps.Length; i++)
        {
            for (int j = 0; j < maps[i].Length; j++)
            {
                if (maps[i][j] != 'X' && found[i, j] == false)
                {
                    answer.Add(BFS(maps, new Pos(i, j)));
                }
            }
        }

        if (answer.Count == 0)
            return new int[] { -1 };

        answer.Sort();
        return answer.ToArray();
    }

    public int BFS(string[] maps, Pos start)
    {
        int result = 0;

        //위 좌 아래 오른
        int[] yStick = new int[4] { -1, 0, 1, 0 };
        int[] xStick = new int[4] { 0, -1, 0, 1 };

        Queue<Pos> queue = new Queue<Pos>();
        queue.Enqueue(start);

        found[start.PosY, start.PosX] = true;
        result += int.Parse(maps[start.PosY][start.PosX].ToString());

        while (queue.Count > 0)
        {
            Pos now = queue.Dequeue();

            for (int i = 0; i < 4; i++)
            {
                int yPos = now.PosY - yStick[i];
                int xPos = now.PosX - xStick[i];

                if (yPos > maps.Length - 1 || yPos < 0)
                    continue;
                if (xPos > maps[0].Length - 1 || xPos < 0)
                    continue;

                if (maps[yPos][xPos] == 'X')
                    continue;

                if (found[yPos, xPos] == true)
                    continue;

                found[yPos, xPos] = true;
                queue.Enqueue(new Pos(yPos, xPos));
                result += int.Parse(maps[yPos][xPos].ToString());
            }
        }
        return result;
    }
}

public class Pos
{
    public int PosY;
    public int PosX;

    public Pos(int posY, int posX)
    {
        PosY = posY;
        PosX = posX;
    }
}
728x90