将0所在的行列清零-二维数组和矩阵
作者:互联网
public class 将零所在的行列清零 {
public static void main(String[] args) {
// TODO Auto-generated method stub
int[][] arr =
{{1,2,3,4},
{5,6,0,8},
{9,10,11,12},
{13,14,15,16}};
solve(arr);
Print(arr);
}
public static void solve(int[][] arr) {
int M = arr.length;//行宽
int N = arr[0].length;//列宽
//记录那些行出现了零
int[] rowRecord = new int[M];
//记录那些列出现了零
int[] colRecord = new int[N];
for(int i = 0; i<M; i++) {
for(int j = 0; j<N; j++) {
if(arr[i][j]==0) {
rowRecord[i] = 1;
colRecord[j] = 1;
}
}
}
for(int row =0; row<M; row++) {
for(int col=0; col<N; col++) {
if(rowRecord[row]==1||colRecord[col]==1) {
arr[row][col] = 0;
}
}
}
}
public static void Print(int[][] arr) {
int row = arr.length;
int col = arr[0].length ;
for(int i = 0;i<row;i++) {
for(int j = 0;j<col;j++) {
System.out.print(arr[i][j] +" ");
}
System.out.println();
}
}
}
标签:arr,int,矩阵,二维,static,new,清零,public 来源: https://blog.csdn.net/weixin_54401017/article/details/122855283