1.7数组-清除行列

题目描述

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

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

测试样例:
[[1,2,3],[0,1,2],[0,0,1]]
返回:[[0,0,3],[0,0,0],[0,0,0]]

解法:循环搜索,统计记录0所在的行列坐标,然后进行清0操作,用两个标志进行标记,行和列是否出现了0
#include <iostream>
#include <vector>
using namespace std;
void printMat(vector<vector<int> > mat, int n) {
    for(int i=0; i < n; i++) { 
        for(int j = 0; j < n; j++)
            cout << mat[i][j] << "   ";
            cout << endl;
    }
}
vector<vector<int> > clearZero(vector<vector<int> > mat, int n) {
        // write code here
        //循环搜索,统计记录0所在的行列坐标,然后进行清0操作
        vector<int> rol(n), col(n);
		for(int i = 0; i < n; i++) {
			for(int j = 0; j < n; j++) {
				if(mat[i][j] == 0) {
				col[j] = 1;	
				rol[i] = 1;
				}
			}
		}
		for(int i = 0; i < n; i++) { 
			for(int j = 0; j < n; j++) {
			    if(rol[i] == 1 || col[j] == 1)
				mat[i][j] = 0;
		      }
		}
		printMat(mat, n);	
		return mat;
  
}

int main(int argc, char** argv) {
    int n = 5;
    vector<vector<int> > array(n); //3个向量
    for(int i = 0; i < n; i++) {
        array[i].resize(n);//设置数组的大小3X3
        }              
    for(int i = 0; i < n; i++) {
       for(int j = 0; j < n; j++) {
        array[i][j] = (n * i - 5);     
       }
    }
    printMat(array, n);
    clearZero(array, n);
    return 0;
}

  

原文地址:https://www.cnblogs.com/xiaohaigege/p/5177908.html