3. 魔方陣

矩陣選轉浪費了我一點時間,不過這題基本也是照題目做就好

# 旋轉90度(一定要建立tmp陣列)的mapping

順時針 tmp[x, lastIndex - y] = matrix[y, x];

逆時針則為 tmp[lastIndex - x, y] = matrix[y, x];

int[,] mod = new int[3, 3]; // y,x

int y = 0;
int x = 1;

int n = 1;
for (int i = 0; i < 9; i++)
{
    mod[y, x] = n;

    // for next
    n++;

    y--;
    x++;

    if (y == -1 && x == 3)
    {
        x = 2;
        y = 1;
    }

    if (x == 3) x = 0;
    if (y == -1) y = 2;


    if (mod[y, x] != 0)
    {
        x--;
        if (x == -1) x = 2;
        y++;
        if (y == 3) y = 0;

        y++;
    }
}

void print()
{
    for (int i = 0; i < 3; i++)
    {
        for (int j = 0; j < 3; j++)
            Console.Write(mod[i, j] + " ");
        Console.WriteLine();
    }
    Console.WriteLine();
}

print(); // first one

void flip()
{
    for (int i = 0; i < 3; i++)
    {
        int tmp = mod[i, 0];
        mod[i, 0] = mod[i, 2];
        mod[i, 2] = tmp;
    }
}

void rotate()
{
    int[,] tmp = new int[3, 3];
    for (y = 0; y < 3; y++)
    {
        for (x = 0; x < 3; x++)
        {
            tmp[x, 2 - y] = mod[y, x];
        }
    }
    mod = tmp;
}

for (int i = 0; i < 3; i++)
{
    rotate();
    print();
}

rotate(); // restore

flip();
print();
for (int i = 0; i < 3; i++)
{
    rotate();
    print();
}

Last updated