• + 0 comments

    I do like this. 1st. Unroll the input matrix to long list. (imagine the list 9 items was rolled in clockwise direction to create a 3x3 matrix),

    2nd. Create the unrolled List of the Magic Square , since magic square can rotate or flip, so the List has some repeat pattern, and I have to create another reverse List.

    ``List<int> rightRotateList 
            = new List<int>{8,3,4,9,2,7,6,1,8,3,4,9,2,7,6};
        List<int> leftRotateList
            = new List<int>(rightRotateList);
        leftRotateList.Reverse();
    

    Notice I have exclude the center number of magic square, number 5, since it's unchanged in every version of magic square 3x3.

    3rd. Calculate the cost and compare. Here is the full code in C#

       ````
     public static int formingMagicSquare(List<List<int>> s)
    
    {
        List<int> costList = new List<int>();
    
        List<int> sToList = s[0];
        sToList.Add(s[1][2]);
        sToList.Add(s[2][2]);
        sToList.Add(s[2][1]);
        sToList.Add(s[2][0]);
        sToList.Add(s[1][0]);
    
        List<int> rightRotateList 
            = new List<int>{8,3,4,9,2,7,6,1,8,3,4,9,2,7,6};
        List<int> leftRotateList
            = new List<int>(rightRotateList);
        leftRotateList.Reverse();
    
        for (int i = 0 ; i < 4 ; i++)
        {
            var costRight = 0 ;
            var costLeft = 0 ;
            for (int j = 0 ; j < sToList.Count ; j++)
            {
                costRight += Math.Abs(sToList[j] - rightRotateList[i*2 + j]);
                costLeft += Math.Abs(sToList[j] - leftRotateList[i*2 + j]);
            }
            var centerMatrixDiff = Math.Abs(s[1][1] - 5);
            costList.Add(costRight + centerMatrixDiff);
            costList.Add(costLeft + centerMatrixDiff);
    
        }
    
        return costList.Min();
        // return costList;
    
    }
    

    ` 4th. It's easier to explain in image, but I don't know how to upload here. So I uploaded to this image hosting service https://ibb.co/sjwBpwZ