알고리즘/programmers

[PCCP 기출문제] 2번 / 석유 시추

꾸준함. 2023. 11. 28. 21:19

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

 

프로그래머스

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

programmers.co.kr

 

간단하게 풀 수 있는 BFS 문제였습니다.

시추관을 수직으로 꽂기 때문에 각 x 좌표마다 석유를 얼마나 뽑을 수 있는지 구하면 되는 문제였습니다.

 

알고리즘은 아래와 같습니다.

1. land 이차원 벡터를 순회하며 BFS 알고리즘을 통해 뽑을 수 있는 석유의 양을 구합니다.

1.1 핵심은 각 x 좌표마다 석유를 얼마나 뽑을 수 있는지를 구하는 것이기 때문에 1번에서 구한 석유의 양을 maxOil[석유가 분포되어 있는 각 x 좌표]에 더해줍니다.

2. 1번에서 구한 maxOil 배열 내 최대 값을 반환해줍니다.

 

#include <string>
#include <vector>
#include <queue>
#include <set>
#include <algorithm>
using namespace std;
const int MAX = 500 + 5;
typedef struct
{
int y, x;
} Dir;
Dir moveDir[4] = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};
bool visited[MAX][MAX];
int maxOil[MAX];
int solution(vector<vector<int>> land) {
int N = land.size();
int M = land[0].size();
for (int y = 0; y < N; y++)
{
for (int x = 0; x < M; x++)
{
if (!land[y][x] || visited[y][x])
{
continue;
}
set<int> xSet;
queue<pair<int, int>> q;
q.push({y, x});
visited[y][x] = true;
int cnt = 0;
while (!q.empty())
{
int curY = q.front().first;
int curX = q.front().second;
xSet.insert(curX);
cnt++;
q.pop();
for (int k = 0; k < 4; k++)
{
int nextY = curY + moveDir[k].y;
int nextX = curX + moveDir[k].x;
if (nextY < 0 || nextY >= N || nextX < 0 || nextX >= M)
{
continue;
}
if (visited[nextY][nextX] || !land[nextY][nextX])
{
continue;
}
visited[nextY][nextX] = true;
q.push({nextY, nextX});
}
}
for (int x : xSet)
{
maxOil[x] += cnt;
}
}
}
sort(maxOil, maxOil + MAX);
return maxOil[MAX - 1];
}
view raw .cpp hosted with ❤ by GitHub

 

개발환경: Programmers IDE 

 

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

반응형

'알고리즘 > programmers' 카테고리의 다른 글

[Programmers] 등대  (0) 2023.12.13
[PCCP 기출문제] 4번 / 수레 움직이기  (2) 2023.11.29
[PCCP 기출문제] 1번 / 붕대 감기  (0) 2023.11.27
[Programmers] 카운트 다운  (0) 2023.11.16
[Programmers] 부대복귀  (0) 2023.11.04