• + 1 comment

    C# solution

    我的想法是: 將3 x 3的magic square除了中間的5之外視為一個環: 因為5一定在最中間 所以我們只要將來源(List s)與標準的magic square(這裡是 Array magic)做比較就可以了 過程中,順向的要比較,逆向的也要比較 順向的:4→9→2→7→6→1→8→3,下一輪:2→7→6→1→8→3→4→9,每次前進2格,以此類推… 逆向的:8→1→6→7→2→9→4→3,下一輪:6→7→2→9→4→3→8→1,每次前進2格,以此類推…

    My opinion is: Think of the 3 x 3 magic square as a ring except for the 5 in the middle: Because 5 must be in the middle So we just compare the source (List s) with the standard magic square (Array magic in this case) In the process, you need to compare things going forward, and you also need to compare things going backward. In the forward direction: 4→9→2→7→6→1→8→3, the next round: 2→7→6→1→8→3→4→9, advancing 2 spaces each time, and so on... Reverse: 8→1→6→7→2→9→4→3, next round: 6→7→2→9→4→3→8→1, advance 2 spaces each time, and so on...

    public static int formingMagicSquare(List<List<int>> s)
        {
            int[] magic = { 4, 9, 2, 7, 6, 1, 8, 3, 4, 9, 2, 7, 6, 1, 8 };
            var sToInt = new List<int>() { s[0][0], s[0][1], s[0][2], s[1][2], s[2][2], s[2][1], s[2][0], s[1][0] };
            var min = int.MaxValue;
            for (int i = 0; i < sToInt.Count; i += 2)
            {
                int tmp = 0, tmpR = 0;
                for (int j = 0; j < sToInt.Count; j++)
                {
                    tmp += Math.Abs(sToInt[j] - magic[i + j]);
                    tmpR += Math.Abs(sToInt[j] - magic[magic.Length - 1 - i - j]);
                }
                tmp += Math.Abs(s[1][1] - 5);
                tmpR += Math.Abs(s[1][1] - 5);
                min = new int[] { min, tmp, tmpR }.Min();
            }
            return min;
        }