// read the integer n var n = 3 //Int(readLine()!)! // declare 2d array var arr : [[Int]] = [] //var existing = [Int](count: 10, repeatedValue: 0) for i in 0 ..< n { arr.append(readLine()!.characters.split(" ").map{Int(String($0))!}) // arr.append(readline()!.characters.split(separator:maxSplits:omittingEmptySubsequences:) } var good : [[[Int]]] = [[[8, 1, 6], [3, 5, 7], [4, 9, 2]], [[4, 3, 8], [9, 5, 1], [2, 7, 6]], [[2, 9, 4], [7, 5, 3], [6, 1, 8]], [[6, 7, 2], [1, 5, 9], [8, 3, 4]], [[6, 1, 8], [7, 5, 3], [2, 9, 4]], [[8, 3, 4], [1, 5, 9], [6, 7, 2]], [[4, 9, 2], [3, 5, 7], [8, 1, 6]], [[2, 7, 6], [9, 5, 1], [4, 3, 8]]] func getDiff() -> Int { var diff = 0 var minDiff = 999999999999 for g in 0 ..< 8 { for i in 0 ..< n { for j in 0 ..< n { let number = arr[i][j] // print(number) diff += abs(number - good[g][i][j]) } } // print("diff: ", diff) if diff < minDiff { minDiff = diff } diff = 0 } // print("returning ", minDiff) return minDiff } print(getDiff())