mat[][] 행렬이 있다고 가정합니다. 캐릭터 Z와 P가 있습니다. Z는 좀비이고 P는 식물입니다. 그리고 또 다른 문자 *는 맨땅입니다. 좀비는 식물이 좀비에 인접해 있을 때 식물을 공격할 수 있습니다. 우리는 좀비로부터 안전한 식물의 수를 찾아야 합니다. 행렬이 아래와 같다고 가정 -

따라서 안전한 식물은 단 두 개뿐입니다.
행렬 요소를 요소별로 탐색한 다음 현재 요소가 식물이면 식물이 좀비에 둘러싸여 있는지 확인하고 그렇지 않은 경우 개수를 늘립니다.
예시
#include<iostream>
using namespace std;
bool isZombie(int i, int j, int r, int c, string mat[]) {
if (i < 0 || j < 0 || i >= r || j >= c || mat[i][j] != 'Z')
return false;
return true;
}
int countSafeCells(string matrix[], int row, int col) {
int i, j, count = 0;
for (i = 0; i < row; i++) {
for (j = 0; j < col; j++) {
if (matrix[i][j] == 'P') {
if (!isZombie(i - 1, j - 1, row, col, matrix) && !isZombie(i - 1, j, row, col, matrix)
&& !isZombie(i - 1, j + 1, row, col, matrix) && !isZombie(i, j - 1, row, col, matrix)
&& !isZombie(i, j, row, col, matrix) && !isZombie(i, j + 1, row, col, matrix)
&& !isZombie(i + 1, j - 1, row, col, matrix) && !isZombie(i + 1, j, row, col, matrix)
&& !isZombie(i + 1, j + 1, row, col, matrix)) {
count++;
}
}
}
}
return count;
}
int main() {
string mat[] = { "**P*", "Z***", "*P**", "***P" };
int row = sizeof(mat) / sizeof(mat[0]);
int col = mat[0].length();
cout << "Number of safe cells: " << countSafeCells(mat, row, col);
} 출력
Number of safe cells: 2