题解 | #矩阵乘法#

矩阵乘法

http://www.nowcoder.com/practice/ebe941260f8c4210aa8c17e99cbc663b

  1. a[x][y] b[y][z] , c[x][z]最终结果

  2. c[0][0] => a 0行 b 0列 c[0][1] => a 0行 b 1列 c[1][0] => a 1行 b 0列 c[1][1] => a 1行 b 1列 => 构造两个函数 一个获取数组的列 一个获取数组的行 储存选择ArrayList

import java.util.*;

public class Main{
    public static void main(String[] args){
        Scanner in = new Scanner(System.in);
        int x = in.nextInt();
        int y = in.nextInt();
        int z = in.nextInt();
        int[][] a = new int[x][y];
        int[][] b = new int[y][z];
        for(int i=0;i<x;i++){
            for(int j=0;j<y;j++)
                a[i][j] = in.nextInt();
        }
        for(int i=0;i<y;i++){
            for(int j=0;j<z;j++)
                b[i][j] = in.nextInt();
        }
        int[][] c = new int[x][z];
        for(int i=0;i<x;i++){
            for(int j=0;j<z;j++){
                System.out.print(getvalue(getrow(a,i), getcolumn(b,j))+" ");
            }
            System.out.println();
        }
        
    }
    public static ArrayList getrow(int[][] a,int n){
        ArrayList<Integer> list = new ArrayList<Integer>();
        for(int j=0;j<a[0].length;j++){
            list.add(a[n][j]);
        }
        return list;
    }
    public static ArrayList getcolumn(int[][] a,int n){
        ArrayList<Integer> list = new ArrayList<Integer>();
        for(int j=0;j<a.length;j++){
            list.add(a[j][n]);
        }
        return list;
    }
    public static int getvalue(ArrayList<Integer> list1,ArrayList<Integer> list2){
        int sum=0;
        for(int i=0;i<list1.size();i++){
            sum += list1.get(i)*list2.get(i);
        }
        
        return sum;
    }
}
全部评论

相关推荐

评论
1
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务