qingcheng奕  

http://oj.leetcode.com/problems/set-matrix-zeroes/

因为空间要求原地,所以一些信息就得原地存储。使用第一行第一列来存本行本列中是否有0.另外对于第一个元素[0][0],需要额外处理。

#include <iostream>
#include <vector>
using namespace std;

class Solution {
public:
    void setZeroes(vector<vector<int> > &matrix) {
        int flag = 0;
        int flag2 = 0;
        for(int i = 0;i<matrix.size();i++)
            for(int j = 0;j<matrix[0].size();j++)
            {
                if(matrix[i][j] == 0)
                {
                    if(j==0)
                        flag2 = 1;
                    if(i==0)
                        flag = 1;
                    matrix[0][j] = 0;
                    matrix[i][0] = 0;
                }
            }

        //handle row
        for(int j = 1;j<matrix[0].size();j++)
        {
            if(matrix[0][j] == 0)
                for(int i = 0;i<matrix.size();i++)
                    matrix[i][j] = 0;
        }
        //handle column
        for(int i = 1;i<matrix.size();i++)
        {
            if(matrix[i][0]==0)
            {
                for(int j = 0;j<matrix[0].size();j++)
                {
                    matrix[i][j] = 0;
                }
            }
        }
        //第一行中有0
        if(flag == 1)
        {
            for(int j = 0;j<matrix[0].size();j++)
            {
                matrix[0][j] = 0;
            }
        }
        //第一列中有0
        if(flag2 ==1)
        {
            for(int i = 0;i<matrix.size();i++)
                matrix[i][0] = 0;
        }
        return;
    }
};
int main()
{
    vector<vector<int> > matrix;
    vector<int> row;
    row.push_back(1);
    matrix.push_back(row);
    row[0] = 0;
    matrix.push_back(row);
    row[0] = 3;
    matrix.push_back(row);
    //row.push_back(0);
    //row.push_back(3);
//    row.push_back(4);
    //matrix.push_back(row);

    /*row.clear();
    row.resize(4);
    row[0] = 5;
    row[1] = 6;
    row[2] = 0;
    row[3] = 8;
    matrix.push_back(row);
    row.clear();*/
    Solution myS;
    vector<vector<int> > ans;
    myS.setZeroes(matrix);
    ans = matrix;
    //int ans = myS.longestConsecutive(num);
    return 0;
}

 

 

posted on 2014-01-16 17:02  qingcheng奕  阅读(137)  评论(0编辑  收藏  举报