赞
踩
67.矩阵置零
题目内容:
代码及思路:
1)判断第0行和第0列是否存在0元素;
2)判断除第0行和第0列之外各矩阵位置处是否存在0,若存在,找到对应第0行及第0列位置置0;
3)若第0行第0列位置有0元素,将整行或者整列置0;
- class Solution {
- public:
- void setZeroes(vector<vector<int>>& matrix) {
- int row=matrix.size();
- int col=matrix[0].size();
- bool row0=false,col0=false;
- //判断第0行和第0列是否有0元素
- for(int i=0;i<row;i++)
- {
- if(matrix[i][0]==0)
- col0=true;
- }
- for(int j=0;j<col;j++)
- {
- if(matrix[0][j]==0)
- row0=true;
- }
- //判断剩下矩阵位置是否有0元素
- for(int i=1;i<row;i++)
- {
- for(int j=1;j<col;j++)
- {
- if(matrix[i][j]==0)//对应第0行和第0列位置置0
- {
- matrix[i][0]=0;
- matrix[0][j]=0;
- }
- }
- }
- for(int i=1;i<row;i++)
- {
- for(int j=1;j<col;j++)
- {
- if(matrix[i][0]==0||matrix[0][j]==0) //若第0行或者第0列对应位置为0,则将其对应位置置零
- {
- matrix[i][j]=0;
- }
- }
- }
- if(col0) //第0行或者第0列只要有0,整行整列置0
- {
- for(int i=0;i<row;i++)
- matrix[i][0]=0;
- }
- if(row0)
- {
- for(int j=0;j<col;j++)
- matrix[0][j]=0;
- }
-
- }
- };
![](https://csdnimg.cn/release/blogv2/dist/pc/img/newCodeMoreWhite.png)
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。