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

Leetcode:Set Matrix Zeroes

时间:2015-04-23 13:17:37      阅读:104      评论:0      收藏:0      [点我收藏+]

标签:matrix

Given a m x n matrix, if an element is 0, set its entire row and column to 0. Do it in place.

遍历矩阵,如果遇到等于0的元素,则把该元素所在行的第一个元素和所在列第一个元素置为0。考虑到row0和col0会重合,所以另外设置一个变量col0来表示第一列的情况。

然后从左下角开始,把符合条件的元素置为0。

实现代码:

class Solution {
public:
    void setZeroes(vector<vector<int> > &matrix) {
    int col0 = 1, rows = matrix.size(), cols = matrix[0].size();

    for (int i = 0; i < rows; i++) {
        if (matrix[i][0] == 0) col0 = 0;
        for (int j = 1; j < cols; j++)
            if (matrix[i][j] == 0)
                matrix[i][0] = matrix[0][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;
        }
    }
};


Leetcode:Set Matrix Zeroes

标签:matrix

原文地址:http://blog.csdn.net/wolongdede/article/details/45220099

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