Created
February 13, 2014 04:48
-
-
Save frank4565/8969890 to your computer and use it in GitHub Desktop.
1.7 Write an algorithm such that if an element in an MxN matrix is 0, its entire row and column are set to 0.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include<iostream> | |
using namespace std; | |
const int M = 3; | |
const int N = 4; | |
void setZeros(int matrix[][N]) | |
{ | |
int row[M/sizeof(int)+1]{}; | |
int col[N/sizeof(int)+1]{}; | |
for (int i = 0; i < M; i++) { | |
for (int j = 0; j < N; j++) { | |
if (matrix[i][j] == 0) { | |
row[i/sizeof(int)] |= 1 << i%sizeof(int); | |
col[j/sizeof(int)] |= 1 << j%sizeof(int); | |
} | |
} | |
} | |
for (int i = 0; i < M; i++) { | |
for (int j = 0; j < N; j++) { | |
if ((row[i/sizeof(int)] & (1 << i%sizeof(int))) || | |
(col[j/sizeof(int)] & (1 << j%sizeof(int)))) | |
matrix[i][j] = 0; | |
} | |
} | |
} | |
void print(int matrix[][N]) | |
{ | |
for (int nRow = 0; nRow < M; nRow++) | |
{ | |
for (int nCol = 0; nCol < N; nCol++) | |
cout << matrix[nRow][nCol] << "\t"; | |
cout << endl; | |
} | |
} | |
int main(int argc, char *argv[]) | |
{ | |
int m[][N]{{1,2,3,4},{5,6,0,8},{9,10,11,12}}; | |
print(m); | |
cout << endl; | |
setZeros(m); | |
print(m); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment