考虑给出一个矩阵。我们必须找到矩阵中的腔数。当一个元素周围的所有其他元素都大于该元素时,则将其称为空腔。所以如果矩阵像-
4 | 5 | 6 |
7 | 1个 | 5 |
4 | 5 | 6 |
因此输出为1。
我们只需检查周围的元素并形成决定。
#include<iostream> #define MAX 100 using namespace std; int numberOfCavities(int array[][MAX], int n) { int arr[n + 2][n + 2]; int count = 0; for (int i = 0; i < n + 2; i++) { for (int j = 0; j < n + 2; j++) { if ((i == 0) || (j == 0) || (i == n + 1) || (j == n + 1)) arr[i][j] = INT_MAX; else arr[i][j] = array[i - 1][j - 1]; } } for (int i = 1; i <= n; i++) { for (int j = 1; j <= n; j++) { if ((arr[i][j] < arr[i - 1][j]) && (arr[i][j] < arr[i + 1][j]) && (arr[i][j] < arr[i][j - 1]) && (arr[i][j] < arr[i][j + 1]) && (arr[i][j] < arr[i - 1][j - 1]) && (arr[i][j] < arr[i + 1][j + 1]) && (arr[i][j] < arr[i - 1][j + 1]) && (arr[i][j] < arr[i + 1][j - 1])) count++; } } return count; } int main() { int a[][MAX] = { { 4, 5, 6 }, { 7, 1, 5 }, { 4, 5, 6 }}; int n = 3; cout << "Number of cavities: " << numberOfCavities(a, n); }
输出结果
Number of cavities: 1