Level 0. 안전지대
폭탄과 인접한 칸들만 위험 지역으로 표시하기 때문에 깊이 1까지만 수행하는 BFS라고 볼 수도 있다.
나는 원소에 접근할 때 범위를 검사하기보다는 vector::at() 함수와 예외 처리를 활용했다.
폭탄이 있을 경우 인접 칸들을 위험 지역(2)으로 표시하고 마지막에 안전 지역(0)의 개수를 세어 해결했다.
#include <iostream>
#include <vector>
#include <algorithm>
#include <numeric>
using namespace std;
void setDanger(vector<vector<int>>& board, int i, int j)
{
for (int k = i - 1; k <= i + 1; ++k)
{
for (int l = j - 1; l <= j + 1; ++l)
{
try
{
int& cell = board.at(k).at(l);
if (!cell)
cell = 2;
}
catch (exception& e)
{
continue;
}
}
}
}
int solution(vector<vector<int>> board)
{
int n = board.size();
for (int i = 0; i < n; ++i)
for (int j = 0; j < n; ++j)
if (board[i][j] == 1)
setDanger(board, i, j);
return accumulate(board.begin(), board.end(), 0, [](const int n, const vector<int>& vec) { return n + count(vec.begin(), vec.end(), 0); });
}
'자료구조 & 알고리즘 > 프로그래머스' 카테고리의 다른 글
Level 0. 삼각형의 완성조건 (2) (0) | 2023.01.29 |
---|---|
Level 0. OX퀴즈 (0) | 2023.01.28 |
Level 0. 옹알이 (1) (0) | 2023.01.26 |
Level 0. 등수 매기기 (0) | 2023.01.25 |
Level 0. 평행 (1) | 2023.01.24 |