Write an algorithm such that if an element in an MxN matrix is 0, its entire row and column is set to 0.
#include <iostream>
using namespace std;
void setZero(int **mat, int m, int n) {
bool row[m], col[n];
memset(row, false, sizeof(row));
memset(col, false, sizeof(col));
for (int i = 0; i < m; ++i)
for (int j = 0; j < n; ++j)
if (mat[i][j] == 0) {
row[i] = true;
col[j] = true;
}
for (int i = 0; i < m; ++i)
for (int j = 0; j < n; ++j)
if (row[i] || col[j])
mat[i][j] = 0;
}
int main(int argc, char const *argv[]) {
int **mat;
mat[3][4] = { 1, 2, 0, 4,
4, 0, 8, 10,
3, 8, 0, 12 };
setZero(mat, 3, 4);
for (int i = 0; i < 3; ++i) {
for (int j = 0; j < 4; ++j)
cout << mat[i][j] << ' ';
cout << endl;
}
return 0;
}
上面是我写的代码, 编译的时候显示 error: expected expression
mat[3][4] = { 1, 2, 0, 4,
^
1 error generated.
各位能帮我看一下吗? 小弟水平很烂, 还请大家轻拍.
怎么发帖以后缩进全没了.......
#include <iostream>
using namespace std;
void setZero(int **mat, int m, int n) {
bool row[m], col[n];
memset(row, false, sizeof(row));
memset(col, false, sizeof(col));
for (int i = 0; i < m; ++i)
for (int j = 0; j < n; ++j)
if (mat[i][j] == 0) {
row[i] = true;
col[j] = true;
}
for (int i = 0; i < m; ++i)
for (int j = 0; j < n; ++j)
if (row[i] || col[j])
mat[i][j] = 0;
}
int main(int argc, char const *argv[]) {
int **mat;
mat[3][4] = { 1, 2, 0, 4,
4, 0, 8, 10,
3, 8, 0, 12 };
setZero(mat, 3, 4);
for (int i = 0; i < 3; ++i) {
for (int j = 0; j < 4; ++j)
cout << mat[i][j] << ' ';
cout << endl;
}
return 0;
}
上面是我写的代码, 编译的时候显示 error: expected expression
mat[3][4] = { 1, 2, 0, 4,
^
1 error generated.
各位能帮我看一下吗? 小弟水平很烂, 还请大家轻拍.
怎么发帖以后缩进全没了.......