My Works | Matrix Problem 01



Problem: Set all cells of row i and column j to 0.


Given a matrix of 1s and 0s. Implement an algorithm that sets all cells of row i and column j to 0 if the original matrix has a 0 in cell(i,j). Would the algorithm change if you have to set it to 1 instead of 0?

Solution: The algorithm is as follows,

Mat_one_0_all_0(row,col,mat)
supposing a two dimensional array mat is containing the matrix which is mat[row,col]. Here row is the number of rows and col is the number of column. i, j, m are three loop counter variable.

01. For i = 1 to row
          For j = 1 to col
                    If mat[i,j] = 0 Then
                              For m = 1 to col
                                        mat[i,m] := 0           |Line 01|
                              Next m
                              For m = 1 to row
                                        mat[m,j] := 0           |Line 02|
                              Next m
                    End If
          Next j
      Next i

This will do the job.  Now, this algorithm has to change at Line 01 and Line 02 as,

mat[i,m] := 1
mat[m,j] := 1

respectively if we want to set 1 instead of 0. But, if we have to take decision from the user that what we will have set (1 or 0) when we get a 0, then the algorithm will be changed a little like the following.


Mat_one_0_all_0(row,col,mat)
supposing a two dimensional array mat is containing the matrix which is mat[row,col]. Here row is the number of rows and col is the number of column. i, j, m are three loop counter variable. 'change' is the variable to store the user's choice.

01. Take input in 'change'

02. For i = 1 to row
          For j = 1 to col
                    If mat[i,j] = 0 Then
                              For m = 1 to col
                                        mat[i,m] := change
                              Next m
                              For m = 1 to row
                                        mat[m,j] := change
                              Next m
                    End If
          Next j
      Next i

I hope it will do.

You can download the EXE from this link. [Click Here To Download mat_0_to_0.exe]

Recommended Recommends

Comments

Contact Us