📜  MXN网格中相邻平方数的总和

📅  最后修改于: 2021-05-04 11:58:41             🧑  作者: Mango

给定一个M×N矩阵。任务是计算相邻单元的数量并计算它们的总和。
如果两个单元在水平,垂直或对角线上彼此相邻,则称为已连接。
例子 :

方法:
在am X n网格中,可能有3种情况:

  • 角单元接触3个单元,并且总是有4个角单元。
  • 边缘单元接触5个单元,并且总是有2 *(m + n-4)个边缘单元。
  • 内部单元接触8个单元,并且总是有(m-2)*(n-2)个内部单元。

所以,

Sum = 3*4 + 5*2*(m+n-4) + 8*(m-2)*(n-2) 
    = 8mn - 6m - 6n +4

下面是上述方法的实现:

C++
// C++ implementation of the above approach
 
#include 
using namespace std;
 
// function to calculate the sum of all cells adjacent value
int sum(int m, int n)
{
    return 8 * m * n - 6 * m - 6 * n + 4;
}
 
// Driver program to test above
int main()
{
    int m = 3, n = 2;
    cout << sum(m, n);
 
    return 0;
}


Java
// Java implementation of the above approach
class GFG
{
     
    // function to calculate the sum
    // of all cells adjacent value
    static int sum(int m, int n)
    {
        return 8 * m * n - 6 * m - 6 * n + 4;
    }
     
    // Driver Code
    public static void main (String[] args)
    {
        int m = 3, n = 2;
        System.out.println(sum(m, n));
    }
}
 
// This Code is contributed by AnkitRai01


Python3
# Python3 implementation of the above approach
 
# function to calculate the sum
# of all cells adjacent value
def summ(m, n):
    return 8 * m * n - 6 * m - 6 * n + 4
 
# Driver Code
m = 3
n = 2
print(summ(m, n))
 
# This code is contributed by Mohit Kumar


C#
// C# implementation of the above approach
using System;
class GFG
{
     
    // function to calculate the sum
    // of all cells adjacent value
    static int sum(int m, int n)
    {
        return 8 * m * n - 6 * m - 6 * n + 4;
    }
     
    // Driver Code
    public static void Main (String []args)
    {
        int m = 3, n = 2;
        Console.WriteLine(sum(m, n));
    }
}
 
// This code is contributed by andrew1234


Javascript


输出:
22

时间复杂度: O(1)