《leetCode》:Set Matrix Zeroes
来源:互联网 发布:网络存储器 编辑:程序博客网 时间:2024/05/22 07:57
题目
Given a m x n matrix, if an element is 0, set its entire row and column to 0. Do it in place.Follow up:Did you use extra space?A straight forward solution using O(mn) space is probably a bad idea.A simple improvement uses O(m + n) space, but still not the best solution.Could you devise a constant space solution?
题目大意:在一个m*n的矩阵matrix中,如果matrix[i][j]=0,则将第i行和第j列的全部设置为零;
思路一
暴力搜索法:A simple improvement uses O(m + n) space, but still not the best solution.
#include<stdio.h>#include<stdlib.h>#include<string.h>void setZeroes(int** matrix, int matrixRowSize, int matrixColSize) { if(matrix==NULL||matrixRowSize<1||matrixColSize<1){ return; } //用来记录哪些行那些列要设为零。 bool *row=(bool *)malloc(matrixRowSize*sizeof(bool)); bool *col=(bool *)malloc(matrixColSize*sizeof(bool)); if(row==NULL||col==NULL){ exit(EXIT_FAILURE); } memset(row,true,matrixRowSize*sizeof(bool)); memset(col,true,matrixColSize*sizeof(bool)); for(int i=0;i<matrixRowSize;i++){ for(int j=0;j<matrixColSize;j++){ if(matrix[i][j]==0){ row[i]=false; col[j]=false; } } } //将行为零 for(int i=0;i<matrixRowSize;i++){ if(!row[i]){ for(int j=0;j<matrixColSize;j++){ matrix[i][j]=0; } } } //列变为零 for(int i=0;i<matrixColSize;i++){ if(!col[i]){ for(int j=0;j<matrixRowSize;j++){ matrix[j][i]=0; } } }// for(int i=0;i<matrixRowSize;i++){// for(int j=0;j<matrixColSize;j++){// printf("%d ",matrix[i][j]);// }// printf("\n");// }}//测试代码如下:int main(void){ int row,col; while(scanf("%d %d",&row,&col)!=EOF){ int **matrix=(int **)malloc(row*sizeof(int *)); if(matrix==NULL){ exit(EXIT_FAILURE); } for(int i=0;i<row;i++){ matrix[i]=(int *)malloc(col*sizeof(int)); if(matrix[i]==NULL){ exit(EXIT_FAILURE); } } for(int i=0;i<row;i++){ for(int j=0;j<col;j++){ scanf("%d",&matrix[i][j]); } } setZeroes(matrix,1,1); }}
AC代码如下:
1 0
- LeetCode: Set Matrix Zeroes
- LeetCode Set Matrix Zeroes
- [Leetcode] Set Matrix Zeroes
- LeetCode: Set Matrix Zeroes
- Leetcode: Set Matrix Zeroes
- [LeetCode] Set Matrix Zeroes
- [LeetCode]Set Matrix Zeroes
- [leetcode]Set Matrix Zeroes
- Leetcode:Set Matrix Zeroes
- LeetCode-Set Matrix Zeroes
- [leetcode] Set Matrix Zeroes
- LeetCode - Set Matrix Zeroes
- Set Matrix Zeroes leetcode
- 【Leetcode】Set Matrix Zeroes
- 【leetcode】Set Matrix Zeroes
- Leetcode: Set Matrix Zeroes
- Leetcode Set Matrix Zeroes
- LeetCode | Set Matrix Zeroes
- [Sort]归并排序
- 弱散列映射表:WeakHashMap
- UDP和TCP通信机制(实现简单的数据发送与接收)
- 视觉感知特性 【1】人类视觉系统的信息处理机制的4个特性
- Android 设置禁止横屏失效解决方法
- 《leetCode》:Set Matrix Zeroes
- 使用BeautifulSoup爬取药智标准网数据(更改)
- 程序模拟分页系统的地址变换过程
- C语言中变量的属性(auto static register)
- BP神经网络——如何进行权值的初始化
- 1027. Colors in Mars (20)
- 响应式布局
- Android 添加手势操作
- 又一个11月悄然过去——致英语