Often, when we facing such problems we can query with a help of Linq:
using System.Linq;
...
private static diagonalDifference(List<List<int>> arr) => Math.Abs(arr
.Select((line, index) => line[index] - line[line.Count - 1 - index])
.Sum());
If you prefer good old for
loop (please, note, that we want just one loop):
private static diagonalDifference(List<List<int>> arr) {
int result = 0;
for (int i = 0; i < arr.Count; ++i)
result += arr[i][i] - arr[i][arr.Count - 1 - i];
return Math.Abs(result);
}
What's going on? We scan matrix (arr
) line
by line an sum the difference between left and right diagonal items:
6, 2, 3 -> 6 - 3 == 3
1, 8, 2 8 - 8 == 0
3, 4, 7 7 - 3 == 4
----------
7 in total
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…