728x90
반응형
🔗 문제 링크
https://school.programmers.co.kr/learn/courses/30/lessons/159993?language=cpp#
프로그래머스
코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.
programmers.co.kr
반응형
728x90
👩💻 코드
#include <string>
#include <vector>
#include <queue>
using namespace std;
struct position{
int x;
int y;
int count;
};
int BFS(vector<string> &maps, position start, char target){
int width = maps.size();
int height = maps[0].size();
vector<vector<bool>> visited(width, vector<bool> (height, false));
queue<position> q;
int nextX[4] = { 0, 1, 0, -1};
int nextY[4] = { 1, 0, -1, 0};
q.push({start.x, start.y, 0});
visited[start.x][start.y] = true;
while(!q.empty()){
position pos = q.front();
int x = pos.x;
int y = pos.y;
int count = pos.count;
char road = maps[x][y];
q.pop();
if(road == target){
return count;
}
for(int i=0; i<4; i++){
int newX = x + nextX[i];
int newY = y + nextY[i];
if(newX < width && newX >= 0 && newY < height && newY >= 0 && !visited[newX][newY] && maps[newX][newY] != 'X'){
q.push({newX, newY, count + 1});
visited[newX][newY] = true;
}
}
}
return -1;
}
int solution(vector<string> maps) {
position start;
position lever;
position exit;
for (int i = 0; i < maps.size(); i++) {
for (int j = 0; j < maps[0].size(); j++) {
if (maps[i][j] == 'S'){
start = {i, j, 0};
}
if (maps[i][j] == 'L'){
lever = {i, j, 0};
}
if (maps[i][j] == 'E'){
exit = {i, j, 0};
}
}
}
int toLever = BFS(maps, start, 'L');
if (toLever == -1) {
return -1;
}
int toExit = BFS(maps, lever, 'E');
if (toExit == -1) {
return -1;
}
return toLever + toExit;
}
📝 풀이
시작 지점에서 레버까지, 레버에서 출구까지의 최단 경로를 BFS 알고리즘으로 구합니다.
둘 중 하나라도 경로를 찾지 못 하면 -1을 return 합니다.
728x90
반응형
'코딩테스트 > 프로그래머스' 카테고리의 다른 글
[프로그래머스] 행렬 테두리 회전하기 (1) | 2024.10.03 |
---|---|
[프로그래머스] [3차] 방금그곡 (0) | 2024.10.01 |
[프로그래머스] 배달 (1) | 2024.09.07 |
[프로그래머스] 숫자 카드 나누기 (0) | 2024.09.06 |
[프로그래머스] 메뉴 리뉴얼 (1) | 2024.09.06 |