Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> C++

Tìm ô an toàn trong ma trận trong C++


Cho ma trận ký tự Z (living dead), P (cây), * (đất trống). Cây an toàn nếu không bị Z tấn công (Z tấn công 8 ô quanh). Đếm số cây an toàn.

Duyệt ma trận, với mỗi P kiểm tra 8 hướng xung quanh, nếu không có Z thì tăng đếm.

Ví dụ

#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); }

Kết quả

Number of safe cells: 2