编写一个算法,若M*N矩阵中某个元素为0,则将其所在的行与列清零。
package test; public class SetZero { public static void setZero(int[][] matrix){ if(matrix==null || matrix.length==0 || matrix[0]==null || matrix[0].length==0) return; int m = matrix.length; int n = matrix[0].length; boolean[] rows = new boolean[m]; boolean[] cols = new boolean[n]; for(int i=0; i<m; i++) for(int j=0; j<n; j++) if(matrix[i][j]==0){ rows[i] = true; cols[j] = true; } for(int i=0; i<m; i++) for(int j=0; j<n; j++) if(rows[i] || cols[j]) matrix[i][j] = 0; } public static void main(String[] args) { // TODO Auto-generated method stub int[][] case1 = null; int[][] case2 = { {0,2,3}, {4,0,6}, {7,8,0} }; int[][] testCase = case2; setZero(testCase); for(int i=0; i<testCase.length; i++){ for(int j=0; j<testCase[0].length; j++){ System.out.print(testCase[i][j]); System.out.print(" "); } System.out.println(); } } }