Created
June 23, 2014 19:37
-
-
Save yokiy/cf901aebcace092fdfeb to your computer and use it in GitHub Desktop.
cc 1.7
This file contains 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
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. | |
# deal matrix as a list | |
def listIndex(x, y, n): | |
return y + x * n | |
def toList(matrix, m, n): | |
global listm | |
listm = list() | |
#write matrix to list | |
for i in range(n): | |
for j in range(m): | |
# listm.insert(listIndex(i, j ,n),matrix[i][j]) | |
listm.append(matrix[i][j]) | |
print ('original matrix:', listm) | |
return listm | |
def checkzeroes(matrix, m, n): | |
global row | |
row = [False for i in range(n)] | |
global col | |
col = [False for i in range(m)] | |
for i in range (n): | |
for j in range (m): | |
if matrix[i][j] == 0: | |
row[i] = True | |
col[j] = True | |
print row, col | |
return (row, col) | |
def setzeroes(matrix, m, n): | |
toList(matrix, m, n) | |
checkzeroes(matrix, m, n) | |
for i in range(n): | |
for j in range(m): | |
if (row[i] or col[j]): | |
listm[listIndex(i, j, n)] = 0 | |
return listm | |
#test case | |
m = 3 | |
n = 3 | |
matrix = [(1,2,3), (2,5,8), (0,3,6)] | |
setzeroes(matrix, m, n) | |
print 'After setzeroes:' | |
for i in range(m*n): | |
print (listm[i]), | |
if (i+1) % m == 0: | |
print('\n') | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment