diagonal-sum.dart (871B)
1 //Given a matrix return the sum of all the values in the 2 //diagnols from top left to bottom right and top right to 3 //bottom left. 4 //Ex. 5 //1 2 3 6 //3 4 5 7 //2 4 5 8 //The output would be 15 because you add up 1 + 4 + 5 9 //and then add 3 + 2 onto that. Since 4 is the shared center 10 //that will not be added on twice hence me zeroing it out in the 11 //code below. 12 //The time complexity of this code is O(n) where n is the size of the matrix. 13 //Time: 388ms Beats: 100% 14 //Memory: 144.6MB Beats: 100% 15 16 17 class Solution { 18 int diagonalSum(List<List<int>> mat) { 19 int total = 0; 20 for(int i = 0 ; i < mat[0].length; ++i){ 21 total += mat[i][i]; 22 mat[i][i] = 0; 23 } 24 int count = 0; 25 for(int i = mat[0].length - 1 ; i >= 0 ; --i){ 26 print(mat[count][i]); 27 total += mat[count][i]; 28 count += 1; 29 } 30 return total; 31 } 32 }