srnldai
srnldai

Reputation: 285

Algorithm for traversing all lines in the n×n grid?

Use a two-dimensional array to represent a nxn grid.

var grid = new int[n,n];

n*n grid

Note that there are two more diagonal lines.

Upvotes: 2

Views: 119

Answers (1)

TemaTre
TemaTre

Reputation: 1424

If i will solve this problem. I will make so.

Create extension method for Int[] (So, you can create your own class. But it's another way. I want to show light waight solution)

    public static class IntAsMatrixExtensions {

        public const int MatrixColumsCount = 3;

        public static int At(this int[] matrix, int i, int j)
        {
            return matrix[i * MatrixColumsCount + j];
        }

        public static int[] Create()
        {
            var grid = new int[MatrixColumsCount*MatrixColumsCount] {
                1,2,3,
                4,5,6,
                7,8,9
            };

            return grid;
        }
    }

Then first you should print matrix:

        for(int i = 0; i < IntAsMatrixExtensions.MatrixColumsCount; i++)
        {
            for(int j = 0; j < IntAsMatrixExtensions.MatrixColumsCount; j++)
            {
                Console.Write(grid.At(i, j));
            }

            Console.WriteLine();
        }

Then print transponated matrix:

        for(int i = 0; i < IntAsMatrixExtensions.MatrixColumsCount; i++)
        {
            for(int j = 0; j < IntAsMatrixExtensions.MatrixColumsCount; j++)
            {
                Console.Write(grid.At(j, i)); //!!! i and j is swithed
            }

            Console.WriteLine();
        }

Then print diag:

        //Print diag
        for(int i = 0; i < IntAsMatrixExtensions.MatrixColumsCount; i++)
        {
            Console.Write(grid.At(i, i)); //!!! i and j is swithed
        }

Then print inverse diag:

        for(int i = 0; i < IntAsMatrixExtensions.MatrixColumsCount; i++)
        {
            Console.Write(grid.At(i, IntAsMatrixExtensions.MatrixColumsCount - i - 1)); //!!! i and j is swithed
        }

Here is example on fiddle https://dotnetfiddle.net/pyX31r

Upvotes: 1

Related Questions