문제
c#으로 처음 알고리즘을 풀다 보니, 기본 문법 관련하여 모르는 것이 많아 어려움을 겪었다.
문제 자체는 기본적인 BFS문제로 난이도가 높게 느껴지진 않았다.
코드
using System;
using System.Collections.Generic;
public class Solution
{
public int solution(int[,] maps)
{
int answer = 0;
bool[,] visited = new bool[maps.GetLength(0), maps.GetLength(1)];
BFS(maps, visited, (0, 0));
if (maps[maps.GetLength(0) - 1, maps.GetLength(1) - 1] == 1)
answer = -1;
else
answer = maps[maps.GetLength(0) - 1, maps.GetLength(1) - 1];
return answer;
}
public void BFS(int[,] maps, bool[,] visited, (int,int) start)
{
Queue<(int,int)> q = new Queue<(int, int)>();
// 남 동 북 서
int[] dx = new int[] { 0, 1, 0, -1 };
int[] dy = new int[] { 1, 0, -1, 0 };
q.Enqueue(start);
visited[start.Item1, start.Item2] = true;
while(q.Count > 0)
{
(int x, int y) = q.Dequeue();
for (int i = 0; i < 4; i++)
{
int nx = dx[i] + x;
int ny = dy[i] + y;
// nx,ny가 범위 안이고 벽이 아니고 방분하지 않은 곳일 때
if(nx >= 0 && ny >= 0 && nx < maps.GetLength(0) && ny < maps.GetLength(1) && maps[nx, ny] != 0 && !visited[nx, ny])
{
if (nx == maps.GetLength(0) && ny == maps.GetLength(1))
{
return;
}
visited[nx, ny] = true;
q.Enqueue((nx, ny));
maps[nx, ny] = maps[x, y] + 1;
}
}
}
}
}
프로그래머스
코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.
programmers.co.kr
'Algorithm > Programmers' 카테고리의 다른 글
[프로그래머스] 12978 파이썬 - 배달 (0) | 2024.09.09 |
---|---|
[프로그래머스] 67256 파이썬 - 키패드 누르기 (2) | 2024.09.05 |
[프로그래머스] 178870 파이썬 - 연속된 부분 수열의 합 (투포인터 알고리즘) (0) | 2024.04.12 |
[프로그래머스] 92334 파이썬 - 신고 결과 받기 (0) | 2024.04.11 |
[프로그래머스] 133502 파이썬 - 햄버거 만들기 (0) | 2024.04.08 |