프로그래머스
코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.
programmers.co.kr
- 단순한 bfs 문제
- 연결된 같은 색상으로 이루어진 영역의 개수와, 가장 넓은 영역의 넓이를 구하는 문제
> 정답률이 낮아서 좀 난이도가 있는 문제인가 싶었는데 열어보니 그냥 bfs로 해결하면 되는 문제였다.
#include <iostream>
#include <vector>
#include <queue>
#include <algorithm>
using namespace std;
int dirX[4] = {0, 1, 0, -1};
int dirY[4] = {1, 0, -1, 0};
bool visited[101][101];
//bfs
int bfs(int i, int j, int m, int n, vector<vector<int>> picture) {
int color = picture[i][j];
int size = 1;
queue<pair<int, int>> q;
q.push({i, j});
visited[i][j] = true;
while(!q.empty()) {
int curX = q.front().first;
int curY = q.front().second;
q.pop();
// 4방향으로 이동
for(int i = 0; i < 4; i++) {
int nx = curX + dirX[i];
int ny = curY + dirY[i];
if(nx >= 0 && nx < m && ny >= 0 && ny < n) {
// 다음으로 방문한 좌표의 색상이 color와 같고 방문한 적 없으면
if(picture[nx][ny] == color && !visited[nx][ny]) {
// 방문 여부 갱신
visited[nx][ny] = true;
// 방문 좌표 갱신
q.push({nx, ny});
// 영역 너비 증가
size++;
}
}
}
}
return size;
}
// 전역 변수를 정의할 경우 함수 내에 초기화 코드를 꼭 작성해주세요.
vector<int> solution(int m, int n, vector<vector<int>> picture) {
int number_of_area = 0;
int max_size_of_one_area = 0;
// 방문 배열 초기화
for(int i = 0; i < m; i++)
for(int j = 0; j < n; j++)
visited[i][j] = false;
// 색이 칠해져 있고 방문한적 없으면 bfs 수행
for(int i = 0; i < m; i++) {
for(int j = 0; j < n; j++) {
if(picture[i][j] != 0 && !visited[i][j]) {
// 가장 넓은 영역 구하기
max_size_of_one_area = max(max_size_of_one_area, bfs(i, j, m, n, picture));
// 영역 개수 증가
number_of_area++;
}
}
}
vector<int> answer(2);
answer[0] = number_of_area;
answer[1] = max_size_of_one_area;
return answer;
}
'프로그래머스 > 2레벨' 카테고리의 다른 글
[프로그래머스/C++] 거리두기 확인하기 (0) | 2024.03.12 |
---|---|
[프로그래머스/C++] 교점에 별 만들기 (0) | 2024.03.12 |
[프로그래머스/C++] 혼자 놀기의 달인 (0) | 2024.03.10 |
[프로그래머스/ C++] 디펜스 게임 (0) | 2024.03.10 |
[프로그래머스/C++] 미로 탈출 (0) | 2024.03.10 |