zoukankan      html  css  js  c++  java
  • 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;
    }
    

      

  • 相关阅读:
    集合的代数运算
    集合的代数运算
    poj1639 Picnic Planning,K度限制生成树
    C/C++学习站点资源
    Mustache 使用心得总结
    PostgreSQL服务端监听设置及client连接方法
    【线性规划与网络流24题】汽车加油行驶问题 分层图
    linux系统下信号具体解释2
    【数据结构】栈-数组的实现
    EJB究竟是什么,真的那么神奇吗??
  • 原文地址:https://www.cnblogs.com/xiaohaigege/p/5177908.html
Copyright © 2011-2022 走看看