九度——题目1001:A+B for Matrices
This time, you are supposed to find A+B where A and B are two matrices, and then count the number of zero rows and columns.
The input consists of several test cases, each starts with a pair of positive integers M and N (≤10) which are the number of rows and columns of the matrices, respectively. Then 2*M lines follow, each contains N integers in [-100, 100], separated by a space. The first M lines correspond to the elements of A and the second M lines to that of B.
The input is terminated by a zero M and that case must NOT be processed.
For each test case you should output in one line the total number of zero rows and columns of A+B.
2 21 11 1-1 -110 92 31 2 34 5 6-1 -2 -3-4 -5 -60
15
2011年浙江大学计算机及软件工程研究生机试真题
import java.util.Scanner; public class Main{ /** * @param args */ public static void main(String[] args) { Scanner cin = new Scanner(System.in); int a1[][], a2[][], rows, columns, count; boolean isZero; while (cin.hasNext()) { count = 0; rows = cin.nextInt(); if (rows == 0) { return; } columns = cin.nextInt(); // 开辟空间 a1 = new int[rows][]; for (int i = 0; i < rows; i++) { a1[i] = new int[columns]; } a2 = new int[rows][]; for (int i = 0; i < rows; i++) { a2[i] = new int[columns]; } // 输入数组 for (int i = 0; i < rows; i++) { for (int j = 0; j < columns; j++) { a1[i][j] = cin.nextInt(); } } for (int i = 0; i < rows; i++) { for (int j = 0; j < columns; j++) { a2[i][j] = cin.nextInt(); } } // 求和 for (int i = 0; i < rows; i++) { for (int j = 0; j < columns; j++) { a1[i][j] = a1[i][j] + a2[i][j]; } } // 统计空行 for (int i = 0; i < rows; i++) { isZero = true; for (int j = 0; j < columns; j++) { if (a1[i][j] != 0) { isZero = false; } } if (isZero) { count++; } } // 统计空列 for (int j = 0; j < columns; j++) { isZero = true; for (int i = 0; i < rows; i++) { if (a1[i][j] != 0) { isZero = false; } } if (isZero) { count++; } } System.out.println(count); } }} /************************************************************** Problem: 1001 User: 忆、瞻 Language: Java Result: Accepted Time:1730 ms Memory:17992 kb****************************************************************/