在矩阵中找出安全单元格
假设我们有一个矩阵 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
广告
数据结构
网络技术
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP