题解 | #A+B for Matrices#

A+B for Matrices

https://www.nowcoder.com/practice/e431b3ae9efa4726b45a659b71abe124

#include <iostream>

using namespace std;

struct Matrix {
    int matrix[10][10];
    int row, col;//行列
    Matrix(int r, int c) {

        row = r;
        col = c;
    }
};

int count = 0;

Matrix add(Matrix x, Matrix y) {
    Matrix c(x.row, x.col);
    for (int i = 0; i < c.row; i++) {
        for (int j = 0; j < c.col; j++) {
            c.matrix[i][j] = 0;
            c.matrix[i][j] += x.matrix[i][j] + y.matrix[i][j];
        }
    }
    return c;
}

int GetNum(Matrix x) {
    count = 0;
    for (int i = 0; i < x.row; i++) { // 先遍历行
        int flag = 1;
        for (int j = 0; j < x.col; j++) {
            if (x.matrix[i][j] != 0) {
                flag = 0;
                break;
            }
        }
        if (flag == 1)
            count++;
    }
    for (int i = 0; i < x.col; i++) { // 遍历列
        int flag = 1;
        for (int j = 0; j < x.row; j++) {
            if (x.matrix[j][i] != 0) {
                flag = 0;
                break;
            }
        }
        if (flag == 1)
            count++;
    }
    return count;
}

void printMatrix(Matrix a) {
    for (int i = 0; i < a.row; i++) {
        for (int j = 0; j < a.col; j++) {
            printf("%d ", a.matrix[i][j]);
        }
        printf("\n");
    }
}

int main() {
    int m, n;
    while (scanf("%d%d", &m, &n) != EOF) {
        if (m == 0) {
            break;
        }
        Matrix a(m, n);
        Matrix b(m, n);
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                scanf("%d", &a.matrix[i][j]);
            }
        }
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                scanf("%d", &b.matrix[i][j]);
            }
        }
        Matrix ans = add(a, b);
        printf("%d\n", GetNum(ans));
    }

    return 0;
}

全部评论

相关推荐

HNU_fsq:建议直接出国,这简历太6了。自愧不如
点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务