Created
September 11, 2020 11:58
-
-
Save khekrn/ea49cd5c0268dadcb92d7024cdb8bd59 to your computer and use it in GitHub Desktop.
Is Magic Square
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
public class MagicSquare { | |
// O(N + N*M) = O(N * M) | |
public boolean isMagicSquare(int[][] arr){ | |
int diag1Sum = 0, diag2Sum = 0; | |
var rowSize = arr.length; | |
var colSize = arr[0].length; | |
for(int i = 0; i < rowSize; i++){ | |
diag1Sum += arr[i][i]; | |
diag2Sum += arr[i][rowSize-1-i]; | |
} | |
if(diag1Sum != diag2Sum){ | |
return false; | |
} | |
for(int i = 0; i < rowSize; i++){ | |
int rowSum = 0, colSum = 0; | |
for(int j = 0; j < colSize; j++){ | |
rowSum += arr[i][j]; | |
colSum += arr[j][i]; | |
} | |
if(rowSum != colSum || rowSum != diag1Sum){ | |
return false; | |
} | |
} | |
return true; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment