Count Magic squares in a grid | Python3 program to count magic squares ; function to check is subgrid is Magic Square ; Elements of grid must contain all numbers from 1 to 9 , sum of all rows , columns and diagonals must be same , i . e . , 15. ; Function to count total Magic square subgrids ; if condition true skip check ; check for magic square subgrid ; return total magic square ; Driver Code ; Function call to print required answer
R = 3 NEW_LINE C = 4 NEW_LINE def magic ( a , b , c , d , e , f , g , h , i ) : NEW_LINE INDENT s1 = set ( [ a , b , c , d , e , f , g , h , i ] ) NEW_LINE s2 = set ( [ 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 ] ) NEW_LINE if ( s1 == s2 and ( a + b + c ) == 15 and ( d + e + f ) == 15 and ( g + h + i ) == 15 and ( a + d + g ) == 15 and ( b + e + h ) == 15 and ( c + f + i ) == 15 and ( a + e + i ) == 15 and ( c + e + g ) == 15 ) : NEW_LINE INDENT return True NEW_LINE DEDENT return false NEW_LINE DEDENT def CountMagicSquare ( Grid ) : NEW_LINE INDENT ans = 0 NEW_LINE for i in range ( 0 , R - 2 ) : NEW_LINE INDENT for j in range ( 0 , C - 2 ) : NEW_LINE INDENT if Grid [ i + 1 ] [ j + 1 ] != 5 : NEW_LINE INDENT continue NEW_LINE DEDENT if ( magic ( Grid [ i ] [ j ] , Grid [ i ] [ j + 1 ] , Grid [ i ] [ j + 2 ] , Grid [ i + 1 ] [ j ] , Grid [ i + 1 ] [ j + 1 ] , Grid [ i + 1 ] [ j + 2 ] , Grid [ i + 2 ] [ j ] , Grid [ i + 2 ] [ j + 1 ] , Grid [ i + 2 ] [ j + 2 ] ) == True ) : NEW_LINE INDENT ans += 1 NEW_LINE DEDENT DEDENT DEDENT return ans NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT G = [ [ 4 , 3 , 8 , 4 ] , [ 9 , 5 , 1 , 9 ] , [ 2 , 7 , 6 , 2 ] ] NEW_LINE print ( CountMagicSquare ( G ) ) NEW_LINE DEDENT