Forming a Magic Square

https://www.hackerrank.com/challenges/magic-square-forming/problem

题目要求把任意一个3阶矩阵转化为Magic Square 要求Cost最低

Magic Square就是将1至9 9个数放入矩阵中 每行每列对角之和相等

可以发现Magic Square只有8种情况,只要将给出的3阶矩阵与8种情况对比查找最少的就可以

class Solution
{

    // Complete the formingMagicSquare function below.
    static int formingMagicSquare(int[][] s)
    {
        int[][ ,] magicSquareList = {new int[3,3]{{8,1,6},{3,5,7},{4,9,2}},
                                       new int[3,3]{{6,1,8},{7,5,3},{2,9,4}},
                                       new int[3,3]{{4,9,2},{3,5,7},{8,1,6}},
                                       new int[3,3]{{2,9,4},{7,5,3},{6,1,8}},
                                       new int[3,3]{{8,3,4},{1,5,9},{6,7,2}},
                                       new int[3,3]{{4,3,8},{9,5,1},{2,7,6}},
                                       new int[3,3]{{6,7,2},{1,5,9},{8,3,4}},
                                       new int[3,3]{{2,7,6},{9,5,1},{4,3,8}}};
        int cost = 0;
        int minCost = 100;
        for (int i = 0; i < 8; i++)
        {
            cost = costToMagicSquare(s, magicSquareList[i]);
            if(minCost > cost)
            {
                minCost = cost;
            }
        }


        return minCost;        
    }

    static void Main(string[] args)
    {
        TextWriter textWriter = new StreamWriter(@System.Environment.GetEnvironmentVariable("OUTPUT_PATH"), true);

        int[][] s = new int[3][];

        for (int i = 0; i < 3; i++)
        {
            s[i] = Array.ConvertAll(Console.ReadLine().Split(' '), sTemp => Convert.ToInt32(sTemp));
        }

        int result = formingMagicSquare(s);

        textWriter.WriteLine(result);

        textWriter.Flush();
        textWriter.Close();
    }

    static int costToMagicSquare(int[][] s, int[,] y)
    {
        int result = 0;
        for (int i = 0; i < 3; i++)
        {
            for (int j = 0; j < 3; j++)
            {
                result += Math.Abs(s[i][j] - y[i,j]);
            }
        }
        return result;
    }
}

点赞