Last active
December 12, 2016 23:21
-
-
Save hmenn/3b96b63cb8ac27c8b5d9a1fe70bce4fc to your computer and use it in GitHub Desktop.
find maximum square matrix with dynamic programming in python
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
| #!usr/bin/python | |
| def printArrayToConsole(arr,startX,startY,endX,endY): | |
| #print(startX,startY,endX,endY) | |
| for i in range(startX,startX+endX): | |
| for j in range(startY,startY+endY): | |
| print(arr[i][j],end="") | |
| print("") | |
| print() | |
| def maxSquareSubset(arr,n,m): | |
| print("->Find maxSquareMatrix") | |
| subsets=[[0 for j in range(m)] for i in range(n)] # create an array filled with 0 | |
| for i in range (0,n): # initialize first column | |
| subsets[i][0] = arr[i][0] | |
| for j in range (0,m): # initialize first row | |
| subsets[0][j] = arr[0][j] | |
| print("Initial dynamic programming array") | |
| printArrayToConsole(subsets,0,0,n,m) | |
| for i in range (1,n): | |
| for j in range(1,m): | |
| if arr[i][j]==1: | |
| # check left-up-and left-up cross off item | |
| # if all of them are 1, we can say there are a matrix | |
| subsets[i][j]=min(subsets[i][j-1],subsets[i-1][j],subsets[i-1][j-1])+1 | |
| else: | |
| subsets[i][j]=0 | |
| print("Step I:",i,"J:",j,"subsets") | |
| printArrayToConsole(subsets,0,0,n,m) | |
| maxS,maxIndexI,maxIndexJ = subsets[0][0],0,0 | |
| # find max value and index | |
| for i in range (1,n): | |
| for j in range(1,m): | |
| if maxS < subsets[i][j]: | |
| maxS=subsets[i][j] | |
| maxIndexI=i | |
| maxIndexJ=j | |
| print("MaxSquareMatrix:","Length:",maxS,"maxIndexI:",maxIndexI,"maxIndexJ:",maxIndexJ) | |
| printArrayToConsole(arr,maxIndexI-maxS+1,maxIndexJ-maxS+1,maxS,maxS) | |
| myArr = [[0,1,1,0,1], | |
| [1,1,0,1,0], | |
| [0,1,1,1,0], | |
| [1,1,1,1,0], | |
| [1,1,1,1,1], | |
| [0,0,0,0,0]] | |
| print("Array to find max square matrix:") | |
| printArrayToConsole(myArr,0,0,6,5) | |
| maxSquareSubset(myArr,6,5) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment