For this question, I implemented this:
public void setZeros (int[][] matrix) {
firstScan(matrix);
secondScan(matrix);
}
public void firstScan(int[][] matrix) {
int i, j;
for (i =0; i < matrix.length; i++) {
for (j = 0; j < matrix[0].length; j++)
{if (matrix[i][j] == 0) {markRowsAndColums(matrix ,i,j);
}}}}
public void secondScan(int[][] matrix) {
int i, j;
for (i =0; i < matrix.length; i++) {
for (j = 0; j < matrix[0].length; j++) { if (matrix[i][j] == -1) {
matrix[i][j]= 0;
}}}}
public void markRowsAndColums (int[][] matrix, int i,int j) {
for ( int x = 0; x< matrix[0].length; x++ ) {
if(matrix[i][x] !=0) {matrix[i][x] = -1;}}
for ( int x = 0; x< matrix.length; x++ ) {
if(matrix[x][j] !=0) {matrix[x][j] = -1;}
}}
My first scan aims to change all rows and columns that have zeros into -1s (but not the zeros).
My second scan aims to convert all the -1s into zeros.
Do you think it is a good solution? Does it work? And I don't know what the runtime of the algorithm is. It would be great if you could give me a hint cuz I really have no idea.
for
loops will take to run, how many times you run them and so on. And what's $n$? The dimension of the matrix? The number of elements in it? – David Richerby Nov 17 '17 at 17:13