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

LeetCode-Set Matrix Zeroes

时间:2015-01-22 09:32:37      阅读:193      评论:0      收藏:0      [点我收藏+]

标签:leetcode

题目链接:https://oj.leetcode.com/problems/set-matrix-zeroes/

题目内容:

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

click to show follow up.

Follow up:

Did you use extra space?
A straight forward solution using O(mn) space is probably a bad idea.
A simple improvement uses O(m + n) space, but still not the best solution.
Could you devise a constant space solution?

解题思路:没想到好的方法,就是最简单的O(m*n)。就是搜到一个0,就把行列都变为0,用了一个符号数组,识别是以前的0,还是变成的0.

class Solution {
public:
    void setZeroes(vector<vector<int> > &matrix) {
    size_t m = matrix.size();
    size_t n = matrix[0].size();
    int s[m][n];
    for(size_t i = 0 ;i != m;i++)
      for(size_t j = 0 ;j !=n;j++)
        s[i][j] = 1;

    for(size_t i = 0 ;i != m;i++)
      for(size_t j = 0 ;j !=n;j++) {
        if(matrix[i][j] == 0 && s[i][j] != -1) {
         for(size_t k = 0; k != n;k++) {
          if(matrix[i][k]!=0 )
            s[i][k] = -1;
          matrix[i][k] = 0;
         }
         for(size_t l = 0; l != m;l++) {
        if(matrix[l][j]!=0 )
            s[l][j] = -1;
           matrix[l][j] = 0;
         }
          
        }
      }
    }
};

转载请注明作者:vanish_dust


LeetCode-Set Matrix Zeroes

标签:leetcode

原文地址:http://blog.csdn.net/vanish_dust/article/details/42985243

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