题解 | #A+B for Matrices#

A+B for Matrices

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

遍历方法数全零行和全零列,通过flag标记,遇到非零元素将标记置为false,并直接结束本轮循环

#include <cmath>
#include <iostream>
using namespace std;
struct matrix {
    int m[10][10];
    int row;
    int col;
    matrix(int r, int c) {
        row = r;
        col = c;
    }
};
matrix add(matrix a, matrix b) {
    matrix ans(a.row, a.col);
    for (int i = 0; i < a.row; i++) {
        for (int j = 0; j < a.col; j++) {
            ans.m[i][j] = a.m[i][j] + b.m[i][j];
        }
    }
    return  ans;
}
int countZero(matrix a) {
    int ans = 0;
    bool flag = true;
    for (int i = 0; i < a.row; i++) {
        flag = true;
        for (int j = 0; j < a.col; j++) {
            if (a.m[i][j] != 0) {
                flag = false;
                break;;
            }
        }
        if (flag == true) ans += 1;
    }
    flag = true;
    for (int i = 0; i < a.col; i++) {
        flag = true;
        for (int j = 0; j < a.row; j++) {
            if (a.m[j][i] != 0) {
                flag = false;
                break;;
            }
        }
        if (flag == true) ans += 1;
    }
    return ans;
}
int main() {
    int M;
    while (cin >> M) { // 注意 while 处理多个 case
        // cout << a + b << endl;
        if (M == 0) break;
        int N;
        cin >> N;
        matrix A(M, N);
        matrix B(M, N);
        for (int i = 0; i < A.row; i++) {
            for (int j = 0; j < A.col; j++) {
                cin >> A.m[i][j];
            }
        }
        for (int i = 0; i < B.row; i++) {
            for (int j = 0; j < B.col; j++) {
                cin >> B.m[i][j];
            }
        }
        matrix sum(A.row, A.col);
        sum = add(A, B);
        cout << countZero(sum) << endl;
    }
}
// 64 位输出请用 printf("%lld")

全部评论

相关推荐

孤寡孤寡的牛牛很热情:为什么我2本9硕投了很多,都是简历或者挂,难道那个恶心人的测评真的得认真做吗
点赞 评论 收藏
分享
评论
点赞
收藏
分享
牛客网
牛客企业服务