알고리즘/programmers

[Programmers] 무인도 여행

꾸준함. 2023. 1. 26. 23:19

문제 링크입니다: https://school.programmers.co.kr/learn/courses/30/lessons/154540

 

프로그래머스

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

programmers.co.kr

 

간단한 BFS 문제였습니다.

 

#include <string>
#include <vector>
#include <queue>
#include <algorithm>
using namespace std;
const int MAX = 100;
typedef struct
{
int y, x;
} Dir;
Dir moveDir[4] = {{ 1, 0 }, { -1, 0 }, { 0, 1 }, { 0, -1}};
bool visited[MAX][MAX];
vector<int> solution(vector<string> maps) {
vector<int> answer;
for (int y = 0; y < maps.size(); y++)
{
for (int x = 0; x < maps[y].size(); x++)
{
if (maps[y][x] == 'X' || visited[y][x])
{
continue;
}
queue<pair<int, int>> q;
q.push({y, x});
visited[y][x] = true;
int sum = maps[y][x] - '0';
while (!q.empty())
{
int y = q.front().first;
int x = q.front().second;
q.pop();
for (int k = 0; k < 4; k++)
{
int nextY = y + moveDir[k].y;
int nextX = x + moveDir[k].x;
if (nextY < 0 || nextY >= maps.size())
{
continue;
}
if (nextX < 0 || nextX >= maps[0].size())
{
continue;
}
if (visited[nextY][nextX] || maps[nextY][nextX] == 'X')
{
continue;
}
visited[nextY][nextX] = true;
sum += maps[nextY][nextX] - '0';
q.push({ nextY, nextX });
}
}
answer.push_back(sum);
}
}
sort(answer.begin(), answer.end());
if (answer.empty())
{
answer.push_back(-1);
}
return answer;
}
view raw .cpp hosted with ❤ by GitHub

 

개발환경: Programmers IDE

지적, 조언, 질문 환영합니다! 질문 남겨주세요~

반응형