在 C++ 中计算矩阵中满足以下条件的单元格数量:当计算相邻单元格的数量时,结果为斐波那契数。


给定一个维度为行 x 列的矩阵 [ ][ ]。目标是找到满足给定条件的矩阵单元格的数量。

单元格矩阵 [i][j] 的值 + 其相邻单元格的数量 = 斐波那契数。

斐波那契数列中的数字:- 0、1、1、2、3、5、8、13、21、43……

让我们通过示例来理解。

例如

输入 - matrix[row][col] = {{1, 4, 1}, {2, 0, 1}, {5, 1, 1}}

输出 - 当计算相邻单元格的数量时,结果为斐波那契数的矩阵中的单元格数量为:4

解释

      0    1   2  

0    1    4    1   

1    2    0    1   

2    5    1    1   

单元格(0,0) → 1+2=3 (2 个相邻单元格 (1,0) 和 (0,1))

单元格(0,2) → 1+2=3

单元格(1,0) → 2+3=5

单元格(2,2) → 1+2=3

输入 - matrix[row][col] =  {{0,0,0}, {0, 1, 0}, {0, 0, 0} }

输出 - 当计算相邻单元格的数量时,结果为斐波那契数的矩阵中的单元格数量为:9

解释

      0    1   2  

0    0    0   0 

1    0    1   0   

2    0    0   0   

单元格(0,0) → 0+2=2 (2 个相邻单元格 (1,0) 和 (0,1)) 同样,单元格 (0,2)、(2,2) 和 (2,0)

单元格(0,1) → 0+3=3 (3 个相邻单元格 (0,1) 和 (0,2) 和 (1,1)) 同样,单元格 (1,0)、(1,2) 和 (2,1)

单元格 (1,1) → 1+4=5 

所有 9 个单元格都被计算在内。

下面程序中使用的方法如下

在任何类型的矩阵中,都只有三种类型的单元格。角单元格将有 2 个相邻单元格,有 3 个相邻单元格的单元格,以及只有 4 个相邻单元格的单元格。将 2、3 或 4 添加到这些单元格的值中,并使用函数 check_fibonacci(int num) 检查总和是否为斐波那契数。

  • 获取一个矩阵[][] 并对其进行初始化。
  • 函数 check_square(long double num) 获取一个数字,如果它是完全平方数,则返回 true。
  • 函数 check_fibonacci(int num) 返回 true,如果 num 是斐波那契数。
  • 如果 check_square(5 * num * num + 4) || check_square(5 * num * num - 4) 返回 true,则 num 是斐波那契数。
  • 函数 Fibonacci_cells(int matrix[row][col]) 返回当计算相邻单元格的数量时,结果为斐波那契数的矩阵中的单元格数量。
  • 将初始计数设置为 0。
  • 使用 for 循环从 i=0 到 i<row 和 j=0 到 j<col 进行遍历。获取 total = matrix[i][j]。
  • 根据其相邻单元格,将 2、3 或 4 添加到 total 中。
  • 如果新的 total 是斐波那契数,则 check_fibonacci(total) 将返回 true,因此递增计数。
  • 在所有 for 循环结束时,返回计数作为结果。

示例

实时演示

#include <bits/stdc++.h>
using namespace std;
#define row 3
#define col 3

bool check_square(long double num) {
   long double val = sqrt(num);
   return ((val - floor(val)) == 0);
}
bool check_fibonacci(int num) {
   return check_square(5 * num * num + 4) || check_square(5 * num * num - 4);
}
int Fibonacci_cells(int matrix[row][col]) {
   int count = 0;

   for (int i = 0; i < row; i++) {
      for (int j = 0; j < col; j++) {
         int total = matrix[i][j];
         if ((i == 0 && j == 0) || (i == row - 1 && j == 0) || (i == 0 && j == col - 1) || (i == row - 1 && j == col - 1)) {
            total = total + 2;
         } else if (i == 0 || j == 0 || i == row - 1 || j == col - 1) {
            total = total + 3;
         } else {
            total = total + 4;
         }
         if (check_fibonacci(total)) {
            count++;
         }
      }
   }
   return count;
}
int main() {
   int matrix[row][col] = {{1, 4,1},{2,0,1},{5,1,1}};
   cout << "Count of cells in a matrix which give a Fibonacci number when the count of adjacent cells is added are: " << Fibonacci_cells(matrix);
   return 0;
}

如果我们运行上述代码,它将生成以下输出:

输出

Count of cells in a matrix which give a Fibonacci number when the count of adjacent cells is added are: 

更新于: 2021年1月29日

82 次查看

启动您的 职业生涯

通过完成课程获得认证

开始学习
广告

© . All rights reserved.