2.1.20—线性表—Set Matrix Zeroes

来源:互联网 发布:sql语法 编辑:程序博客网 时间:2024/06/05 13:29
描述
Given a m × 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?

#include<iostream>#include<vector>#include<string>using namespace std;const int n = 5;void SetMatrixZeros(int a[][n], int m){bool rowflag = false;bool colflag = false;for (int i = 0; i < n; i++){if (a[0][i] == 0){rowflag = true;break;}}for (int i = 0; i < m; i++){if (a[i][0] == 0){colflag = true;break;}}//for (int i = 1; i < m; i++){for (int j = 1; j < n; j++){if (a[i][j] == 0){a[i][0] = 0;a[0][j] = 0;}}}//for (int i = 1; i < m; i++){for (int j = 1; j < n; j++){if (a[i][0] == 0 || a[0][j] == 0)a[i][j] = 0;}}//if (rowflag){for (int i = 0; i < n; i++){a[0][i] = 0;}}if (colflag){for (int j = 0; j < m; j++){a[j][0] = 0;}}}int main(){const int m = 4;int a[m][n] = { { 0, 2, 3, 4, 5 }, { 3, 7, 8, 9, 0 }, { 0, 1, 2, 3, 4 }, { 1, 5, 6, 0, 9 } };SetMatrixZeros(a, m);for (int i = 0; i < m; i++){for (int j = 0; j < n; j++)cout << a[i][j] << " ";cout << endl;}}



原创粉丝点击