Blue Bridge Cup test questions basic exercises matrix multiplication BASIC-17 JAVA

Foreword

I have been conducting interviews recently. Many of the written code is too lazy to post to the blog. It is now filled in, but there may be fewer comments. If you have any questions, please contact me

Exam questions basic exercises matrix multiplication

Resource limit
Time limit: 1.0s Memory limit: 512.0MB

Problem description
  Given an N-th order matrix A, output A to the power of M (M is a non-negative integer)
  For example:
  A =
  1 2
  3 4
  A to the power of 2
  7 10
  15 22

Input format The
  first row is a positive integer N, M (1 <= N <= 30, 0 <= M <= 5), which means the order of the matrix A and the required power. The
  next N rows, N each row Non-negative integer with an absolute value not exceeding 10, describing the value of matrix A

Output format
  outputs a total of N rows, with N integers per row, representing the matrix corresponding to the M-th power of A. Adjacent numbers are separated by a space

Sample input
2 2
1 2
3 4

Sample output
7 10
15 22

Code for this question

import java.util.Scanner;

public class MatrixMulti {

    private static int N;//矩阵A的阶数
    private static int[][] matrix; //矩阵A

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        N = sc.nextInt();
        int M = sc.nextInt(); //要求的幂数
        matrix = new int[N][N];
        for (int i = 0; i < N; i++) {
            for (int j = 0; j < N; j++) {
                matrix[i][j] = sc.nextInt();
            }
        }
        int[][] newMatrix = new int[N][N];
        if (M == 0) {
            for (int i = 0; i < N; i++) {
                newMatrix[i][i] = 1;
            }
        } else {
            newMatrix = matrix;
            for (int i = 0; i < M - 1; i++) {
                newMatrix = matriMultiplication(newMatrix);
            }
        }

        for (int i = 0; i < N; i++) {
            for (int j = 0; j < N; j++) {
                System.out.print(newMatrix[i][j] + " ");
            }
            System.out.println();
        }
    }

    private static int[][] matriMultiplication(int[][] matrixParam) {
        int[][] newMatrix = new int[N][N];
        for (int i = 0; i < N; i++) {
            for (int j = 0; j < N; j++) {
                for (int k = 0; k < N; k++) {
                    newMatrix[i][k] += matrixParam[i][j] * matrix[j][k];
                }
            }
        }
        return newMatrix;
    }
}
Published 113 original articles · Liked 105 · Visitors 20,000+

Guess you like

Origin blog.csdn.net/weixin_43124279/article/details/105419129