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.

二维数组中为0的元素,就把该元素所在的行和列都置为0

思路:

开个结构数组p,用p记录该二维数组中为0的点的i,j脚标。

然后分别遍历p中的行脚标,和列脚标,来设置相应的行和列设为0即可。

用一个bool数组来去除重复行脚标和列脚标,提高效率。

代码:

struct point
{
    int i;
    int j;
};
const int MAXNUM=1000;
class Solution {
public:
    void setZeroes(vector<vector<int> > &matrix) {
        vector<struct point> p;
        p.resize(MAXNUM);
        int p_size=0;
        int m=matrix.size();//
        int n=matrix[0].size();//

        for (size_t i=0;i<m;++i){
            for (size_t j=0;j<n;++j){
                if(matrix[i][j]==0){
                    p[p_size].i=i;
                    p[p_size++].j=j;
                }
            }
        }

        vector<bool> has_been_set_row(MAXNUM,false);
        for (size_t loc=0;loc<p_size;++loc)
        {
            if(!has_been_set_row[p[loc].i]){
                for (int j=0;j<n;++j)
                    matrix[p[loc].i][j]=0;
                has_been_set_row[p[loc].i]=true;
            }
        }

        vector<bool> has_been_set_col(MAXNUM,false);
        for (size_t loc=0;loc<p_size;++loc)
        {
            if(!has_been_set_col[p[loc].j]){
                for (int i=0;i<m;++i)
                    matrix[i][p[loc].j]=0;
                has_been_set_col[p[loc].j]=true;
            }
        }

    }
};

 

posted @ 2014-12-02 10:11  雄哼哼  阅读(138)  评论(0编辑  收藏  举报