您的位置:首页 > 其它

Leetcode:73.Set Matrix Zeroes

2017-11-29 10:50 453 查看
Given a m x n matrix, if an element is 0, set its entire row and column to 0. Do it in place.

public void setZeroes(int[][] matrix) {
int col0 = 1, rows = matrix.length, cols = matrix[0].length;

for (int i = 0; i < rows; i++) {
if (matrix[i][0] == 0) col0 = 0;//这一行的第一个等于0
for (int j = 1; j < cols; j++)
if (matrix[i][j] == 0)      //i行j列等于0
matrix[i][0] = matrix[0][j] = 0; //i行第一个或者j列第一个设置为0
}

//反向遍历
for (int i = rows - 1; i >= 0; i--) {
for (int j = cols - 1; j >= 1; j--)
if (matrix[i][0] == 0 || matrix[0][j] == 0)
matrix[i][j] = 0;
if (col0 == 0) matrix[i][0] = 0;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: