码迷,mamicode.com
首页 > 其他好文 > 详细

73 Set Matrix Zeroes

时间:2015-05-19 12:33:50      阅读:134      评论:0      收藏:0      [点我收藏+]

标签:

public class Solution {
    public void setZeroes(int[][] matrix) {
        if (matrix == null || matrix.length == 0 || matrix[0].length == 0) {
            return;
        }
        
        int row = matrix.length;
        int col = matrix[0].length;
        boolean rowZero = false;
        boolean colZero = false;
        
        for (int i =  0; i < col; i++) {
            if (matrix[0][i] == 0) {
                rowZero = true;
                break;
            }
        }
        
        for (int j = 0; j < row; j++) {
            if (matrix[j][0] == 0) {
                colZero = true;
                break;
            }
        }
        
        for (int i = 1; i < row; i++) {
            for (int j = 1; j < col; j++) {
                if (matrix[i][j] == 0) {
                    matrix[0][j] = 0;
                    matrix[i][0] = 0;
                }
            }
        }
        
        for (int i = 1; i < row; i++) {
            for (int j = 1; j < col; j++) {
                if (matrix[i][0] == 0 || matrix[0][j] == 0) {
                    matrix[i][j] = 0;
                }
            }
        }
        
       if(rowZero){
            for(int i = 0; i < col; i++){
                matrix[0][i] = 0;
            }           
        }
        
        if(colZero){
            for(int i = 0; i < row; i++){
                matrix[i][0] = 0;
            }           
        }
    }
}

写的时候没有单独判断第一行和第一列, 应该提前判断第一行和第一列用不用变为零。 

73 Set Matrix Zeroes

标签:

原文地址:http://www.cnblogs.com/77rousongpai/p/4513751.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!