728x90
https://school.programmers.co.kr/learn/courses/30/lessons/159993
소스코드
using System;
using System.Collections.Generic;
public class Solution
{
static Pos _end;
public int solution(string[] maps)
{
int answerL = 0;
int answerE = 0;
Pos startPos = null;
for (int i = 0; i < maps.Length; i++)
{
int idx = maps[i].IndexOf('S');
if (idx != -1)
{
startPos = new Pos(i, idx);
break;
}
}
answerL = BFS(maps, 'L', startPos);
if (answerL == -1)
return -1;
answerE = BFS(maps, 'E', _end);
if (answerE == -1)
return -1;
return answerL + answerE;
}
public static int BFS(string[] maps, Pos start, char target)
{
if (start == null)
return -1;
//Up = 0, Left = 1, Down = 2, Right = 3
int[] deltaY = new int[] { -1, 0, 1, 0 };
int[] deltaX = new int[] { 0, -1, 0, 1 };
int[,] dist = new int[maps.Length, maps[0].Length];//시작점에서 부터 지점까지의 거리
Queue<Pos> q = new Queue<Pos>();
q.Enqueue(start);
while (q.Count > 0)
{
Pos now = q.Dequeue();
if (maps[now.Y][now.X] == target)
{
_end = now;
return dist[now.Y, now.X];
}
for (int i = 0; i < 4; i++)
{
int nextY = now.Y + deltaY[i];
int nextX = now.X + deltaX[i];
if (nextY >= maps.Length || nextY < 0)
continue;
if (nextX >= maps[0].Length || nextX < 0)
continue;
if (maps[nextY][nextX] == 'X')
continue;
if (dist[nextY, nextX] != 0)//경유한지점
continue;
q.Enqueue(new Pos(nextY, nextX));
dist[nextY, nextX] = dist[now.Y, now.X] + 1;
}
}
return -1;
}
}
public class Pos
{
public int Y;
public int X;
public Pos(int y, int x)
{
Y = y;
X = x;
}
}
728x90
'코딩공부 > 프로그래머스' 카테고리의 다른 글
[프로그래머스]Lv.2 무인도 여행 C#(BFS) (0) | 2023.07.04 |
---|---|
※[프로그래머스]Lv.2 호텔 대실 C# (0) | 2023.06.30 |
※[프로그래머스]Lv.2 과제 진행하기 C# (0) | 2023.06.21 |
※[프로그래머스]Lv.2 요격 시스템 C# (List<(int, int)>) (0) | 2023.06.20 |
※[프로그래머스]Lv.1 문자열 내 마음대로 정렬하기 C#(OrderBy,ThenBy) (0) | 2023.06.19 |