📌  相关文章
📜  生成每行和每一列的乘积为1或-1的矩阵的方法数量

📅  最后修改于: 2021-04-23 19:34:44             🧑  作者: Mango

给定两个整数NM ,任务是找到形成大小为N * M的矩阵(仅由1或-1组成)的方式的数目,以使每一行和每一列中的整数乘积等于1或-1。
例子:

天真的方法:
解决此问题的最简单方法是生成大小为N * M的所有可能矩阵,并为每个矩阵计算所有行和列的乘积,并检查其是否为1或-1。

时间复杂度: O(2 N * M )
辅助空间: O(M * N)

高效方法:
假设前N-1行和前M-1列用1或-1填充。现在,每行最多N-1行和每列最多M-1列的乘积将为1-1 。总共有2种(N-1)*(M-1)种方法来形成大小为(N-1)*(M-1)的矩阵,并用1或-1填充。根据所需的N行和M列乘积,可以相应地填充最后一行。
请按照以下步骤解决问题:

  • 如果N + M偶数
    得到乘积的可能矩阵数为1 = 2 (N-1)*(M-1)
    得到-1的乘积的可能矩阵数= 2 (N-1)*(M-1)
  • 如果N + M奇数
    得到乘积的可能矩阵数为1 = 2 (N-1)*(M-1)
    获得乘积的可能矩阵数为-1 = 0

下面是上述方法的实现:

C++
// C++ implementation of
// the above approach
  
#include 
using namespace std;
  
// Function to return the
// number of possible ways
void Solve(int N, int M)
{
  
    int temp = (N - 1) * (M - 1);
    int ans = pow(2, temp);
  
    // Check if product can be -1
    if ((N + M) % 2 != 0)
        cout << ans;
    else
        cout << 2 * ans;
  
    cout << endl;
}
// Driver Code
int main()
{
    int N = 3;
    int M = 3;
  
    Solve(N, M);
    return 0;
}


Java
// Java implementation of the above approach 
import java.util.Arrays;
  
class GFG{ 
      
// Function to return the
// number of possible ways
static void Solve(int N, int M)
{
    int temp = (N - 1) * (M - 1);
    int ans = (int)(Math.pow(2, temp));
  
    // Check if product can be -1
    if ((N + M) % 2 != 0)
        System.out.print(ans);
    else
        System.out.print(2 * ans);
}
  
// Driver code 
public static void main (String[] args) 
{ 
    int N = 3;
    int M = 3;
      
    Solve(N, M);
} 
} 
  
// This code is contributed by Shubham Prakash


Python3
# Python3 program to implement
# the above approach
# Function to return 
# possible number of ways
def Solve(N, M):
  temp = (N - 1) * (M - 1)
  ans = pow(2, temp)
  
  # Check if product can be -1
  if ((N + M) % 2 != 0):
    print(ans)
    else:
      print(2 * ans)
  
      # driver code
      if __name__ == '__main__':
        N, M = 3, 3
        Solve(N, M)
  
# This code is contributed by Sri_srajit


C#
// C# implementation of the above approach 
using System;
  
class GFG{
      
// Function to return the
// number of possible ways
static void Solve(int N, int M)
{
    int temp = (N - 1) * (M - 1);
    int ans = (int)(Math.Pow(2, temp));
  
    // Check if product can be -1
    if ((N + M) % 2 != 0)
        Console.Write(ans);
    else
        Console.Write(2 * ans);
}
  
// Driver Code
public static void Main(string[] args)
{
    int N = 3;
    int M = 3;
      
    Solve(N, M);
}
}
  
// This code is contributed by rutvik_56


输出:
32

时间复杂度: O(log(N * M))
辅助空间: O(1)