문제 링크입니다: https://school.programmers.co.kr/learn/courses/30/lessons/154540
프로그래머스
코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.
programmers.co.kr
간단한 BFS 문제였습니다.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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; | |
} |

개발환경: Programmers IDE
지적, 조언, 질문 환영합니다! 질문 남겨주세요~
반응형
'알고리즘 > programmers' 카테고리의 다른 글
[Programmers] 흉부외과 또는 일반외과 의사 목록 출력하기 (0) | 2023.01.31 |
---|---|
[Programmers] 뒤에 있는 큰 수 찾기 (0) | 2023.01.28 |
[Programmers] 진료과별 총 예약 횟수 출력하기 (0) | 2023.01.25 |
[Programmers] 과일로 만든 아이스크림 고르기 (0) | 2023.01.24 |
[Programmers] 인사고과 (5) | 2023.01.22 |