https://school.programmers.co.kr/learn/courses/30/lessons/154540
프로그래머스
코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.
programmers.co.kr
풀이
갈 수 없는 지점을 0으로 처리하고, 나머지 숫자를 발견한 지점에서 DFS 또는 BFS를 사용하면 간단히 해결할 수 있다.
#include <string>
#include <vector>
#include <stack>
#include <algorithm>
using namespace std;
int map[101][101];
int dr[4]={0, 1, 0, -1};
int dc[4]={1, 0, -1, 0};
vector<int> solution(vector<string> maps) {
vector<int> answer;
int h = maps.size();
int w = maps[0].size();
for (int i=0; i<h; i++){
for (int j=0; j<w; j++){
if (isdigit(maps[i][j])){
map[i+1][j+1]=maps[i][j]-'0';
}
}
}
for (int i=1; i<=h; i++){
for (int j=1; j<=w; j++){
int sum=0;
if (map[i][j]>0){
// dfs
stack<pair<int, int>> stk;
stk.push({i, j});
sum=map[i][j];
map[i][j]=0;
while (!stk.empty()){
pair<int, int> v=stk.top();
stk.pop();
for (int i=0; i<4; i++){
int nr = v.first + dr[i];
int nc = v.second + dc[i];
if (nr < 1 || nr > h || nc < 1 || nc > w) continue;
if (map[nr][nc]>0){
sum+=map[nr][nc];
map[nr][nc]=0;
stk.push({nr, nc});
}
}
}
}
if (sum>0) answer.push_back(sum);
}
}
sort(answer.begin(), answer.end());
if (answer.empty()) answer.push_back(-1);
return answer;
}
'프로그래머스 > Lv.2' 카테고리의 다른 글
[C++] 프로그래머스 이모티콘 할인행사 (0) | 2023.02.08 |
---|---|
[C++] 프로그래머스 시소 짝꿍 (0) | 2023.02.08 |
[C++] 프로그래머스 숫자 변환하기 (0) | 2023.02.07 |
[C++] 프로그래머스 택배 배달과 수거하기 (0) | 2023.02.07 |
[C++] 프로그래머스 호텔 대실 (0) | 2023.02.07 |