清除行列

题目描述

请编写一个算法,若N阶方阵中某个元素为0,则将其所在的行与列清零。

给定一个N阶方阵int[][](C++中为vector<vector><int>>)mat和矩阵的阶数n,请返回完成操作后的int[][]方阵(C++中为vector<vector><int>>),保证n小于等于300,矩阵中的元素为int范围内。</int></vector></int></vector>

测试样例:

[[1,2,3],[0,1,2],[0,0,1]]
返回:[[0,0,3],[0,0,0],[0,0,0]]

Solution 1(常规思路)

//常规思路,就是找出所有为0的位置,再将对应的行列分别置0,中间需要一个标志
class Clearer {
public:
    vector<vector<int> > clearZero(vector<vector<int> > mat, int n) {
        if(n<=0) return mat;
        int state[n][n];
        memset(state,0,sizeof state);
        queue<pair<int,int>>q;
        for(int i=0;i<mat.size();++i)
            for(int j=0;j<mat[i].size();++j)
                  if(mat[i][j]==0)
                      q.push(pair<int,int>(i,j));
        while(!q.empty())
        {
            pair<int,int>front=q.front();
            q.pop();
            state[front.first][front.second]=1;
            for(int k=0;k<n;++k)
                if(mat[k][front.second]!=0&&state[k][front.second]==0)
                {
                    mat[k][front.second]=0;
                    state[k][front.second]=1;
                }
            for(int k=0;k<n;++k)
                if(mat[front.first][k]!=0&&state[front.first][k]==0)
                {
                    mat[front.first][k]=0;
                    state[front.first][k]=1;
                }
        }
        return mat;
    }
};

Solution 2(行列分开考虑)

publicclassClearer {
    publicint[][] clearZero(int[][] mat, intn) {
        // write code here
        boolean[] rowArray = newboolean[n];
        boolean[] columnArray = newboolean[n];
         //记录为0的位置,把相应的行列位置设为true
        for(int i=0; i<n;i++)
        {
            for(intj=0;j<n;j++)
            {
                if(mat[i][j]==0)
                {
                    rowArray[i]=true;
                    columnArray[j]=true;
                }
            }         
        }
         //遍历找到之前记录的位置,把相应行列赋值为0
        for(int i=0;i<n;i++)
        {
            for(intj=0;j<n;j++)
            {
                if(rowArray[i]||columnArray[j])
                {
                mat[i][j] = 0;
                }
            }
        }
        returnmat;
    }
};

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值