[Programmers] Lv2. ์นด์นด์คํ๋ ์ฆ ์ปฌ๋ฌ๋ง๋ถ | C++
2023. 7. 13. 20:07ใCoding Test/Programmers
๐๋ฌธ์ ๋ณด๋ฌ๊ฐ๊ธฐ
๐จ๐ปํ์ด ๊ณผ์
BFS๋ก ํ ์ ์๋ ์ฌ์ด ๋ฌธ์ ์ ๋๋ค.
- ์์น ๋์ง ์์ ์์ญ์ ์ง๋๊ฐ๋ค.
- ์์น ๋์ด ์๊ณ , ๋ฐฉ๋ฌธํ ์ ์ด ์๋ ํฝ์ ์ด๋ผ๋ฉด, ํด๋น ํฝ์ ์ ๊ธฐ์ค์ผ๋ก ์ํ์ข์ฐ BFS ํ์์ ์์ํ๋ค.
- BFS ํ์์ด ๋๋ฌ๋ค๋ฉด ์์ญ ๊ฐ์๋ฅผ 1๊ฐ ๋๋ ค์ฃผ๊ณ , ์ด์ ์์ญ ํฌ๊ธฐ์ ๋น๊ตํ์ฌ ๋ ํฐ ๊ฐ์ผ๋ก ๊ฐฑ์ ํ๋ค.
โ๏ธ์์ค ์ฝ๋ ๋ฐ ๊ฒฐ๊ณผ
#include <vector>
#include <queue>
using namespace std;
const int DIRECTION_COUNT = 4;
const int rowDirections[DIRECTION_COUNT] = { -1, 1, 0, 0 };
const int colDirections[DIRECTION_COUNT] = { 0, 0, -1, 1 };
struct Pixel {
Pixel() { }
Pixel(int color, int row, int col) : _color(color), _row(row), _col(col) { }
int _color;
int _row;
int _col;
};
int FindArea(vector<vector<Pixel>>& board, vector<vector<bool>>& visited, int m, int n, Pixel selection) {
int area = 1;
visited[selection._row][selection._col] = true;
queue<Pixel> coloredAreas;
coloredAreas.emplace(selection);
while (!coloredAreas.empty()) {
Pixel pixel = coloredAreas.front();
coloredAreas.pop();
for (int i = 0; i < DIRECTION_COUNT; i++) {
int nextRow = pixel._row + rowDirections[i];
int nextCol = pixel._col + colDirections[i];
if (nextRow < 0 or nextRow >= m or nextCol < 0 or nextCol >= n)
continue;
if (board[nextRow][nextCol]._color != pixel._color or board[nextRow][nextCol]._color == 0 or visited[nextRow][nextCol])
continue;
coloredAreas.emplace(Pixel(pixel._color, nextRow, nextCol));
visited[nextRow][nextCol] = true;
area++;
}
}
return area;
}
// ์ ์ญ ๋ณ์๋ฅผ ์ ์ํ ๊ฒฝ์ฐ ํจ์ ๋ด์ ์ด๊ธฐํ ์ฝ๋๋ฅผ ๊ผญ ์์ฑํด์ฃผ์ธ์.
vector<int> solution(int m, int n, vector<vector<int>> picture) {
int number_of_area = 0;
int max_size_of_one_area = 0;
vector<vector<Pixel>> board(m, vector<Pixel>(n));
vector<vector<bool>> visited(m, vector<bool>(n, false));
for (int row = 0; row < m; row++)
for (int col = 0; col < n; col++)
board[row][col] = Pixel(picture[row][col], row, col);
for (int row = 0; row < m; row++) {
for (int col = 0; col < n; col++) {
if (visited[row][col] or board[row][col]._color == 0)
continue;
number_of_area++;
max_size_of_one_area = max(max_size_of_one_area, FindArea(board, visited, m, n, board[row][col]));
}
}
return { number_of_area, max_size_of_one_area };
}
728x90
๋ฐ์ํ
'Coding Test > Programmers' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[Programmers] Lv3. ์ด์ค์ฐ์ ์์ํ | C++ (0) | 2023.09.10 |
---|---|
[Programmers] Lv2. ๋จ์ฒด์ฌ์ง ์ฐ๊ธฐ | C++ (0) | 2023.08.12 |
[Programmers] Lv2. ์์ ๊ฒ์ | C++ (0) | 2023.07.10 |
[Programmers] Lv2. ์ด๋ชจํฐ์ฝ ํ ์ธํ์ฌ | C++ (2) | 2023.07.09 |
[Programmers] Lv2. ์๊ฒฉ ์์คํ | C++ (0) | 2023.07.06 |