728x90
반응형
https://school.programmers.co.kr/learn/courses/30/lessons/1844
프로그래머스
SW개발자를 위한 평가, 교육, 채용까지 Total Solution을 제공하는 개발자 성장을 위한 베이스캠프
programmers.co.kr
일반적인 BFS로 풀었다.
각 칸(경로)마다의 가중치가 없기 때문에, 방문처리만 하며 가장 빠르게 목적지에 도달하는 경로가 최단 거리이다.
#include <vector>
#include <queue>
using namespace std;
int dy[]{ -1, 0, 1, 0 };
int dx[]{ 0, 1, 0, -1 };
int solution(vector<vector<int>> maps)
{
int answer = 1;
vector<vector<bool>> Visit(maps.size(), vector<bool>(maps[0].size(), false));
queue<pair<int, int>> q;
q.push({ 0, 0 });
while (!q.empty())
{
int Size = q.size();
for (int i = 0; i < Size; ++i)
{
int y = q.front().first, x = q.front().second;
q.pop();
if (Visit[y][x]) continue;
Visit[y][x] = true;
for (int j = 0; j < 4; ++j)
{
int ny = y + dy[j], nx = x + dx[j];
if (ny < 0 || nx < 0 || ny > maps.size() - 1 || nx > maps[0].size() - 1 || !maps[ny][nx]) continue;
if (ny == maps.size() - 1 && nx == maps[0].size() - 1) return ++answer;
q.push({ ny, nx });
}
}
answer++;
}
return -1;
}
728x90
반응형
'📕알고리즘 문제 > 📝Programmers' 카테고리의 다른 글
[프로그래머스] Level 2 : 무인도 여행 (0) | 2024.11.25 |
---|---|
[프로그래머스] Level 2 : 뒤에 있는 큰 수 찾기 (0) | 2024.11.24 |
[프로그래머스] Level 2 : 프로세스 (0) | 2024.11.20 |
[프로그래머스] Level 3 : 디스크 컨트롤러 (0) | 2024.11.18 |
[프로그래머스] Level 2 : 최댓값과 최솟값 (0) | 2024.11.11 |