在矩陣中找出安全單元格
假設我們有一個矩陣 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