Answer to Question #332592 in C# for Macky

Question #332592

The first line will contain a message prompt to input the number of rows.


The second line will contain a message prompt to input the number of columns.


The succeeding lines will prompt to input the elements of the matrix.


The last line contains the matrix elements from a spiral form to a straight line.

1
Expert's answer
2022-04-22T16:43:52-0400
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;


class Program
{
    static void Main()
    {
        Console.Write("Input number of rows: ");
        int rows = int.Parse(Console.ReadLine());


        Console.Write("Input number of columns: ");
        int columns = int.Parse(Console.ReadLine());


        int[,] matrix = new int[rows, columns];
        for (int i = 0; i < rows; i++)
        {
            for (int j = 0; j < columns; j++)
            {
                Console.Write($"Input elements {i + 1}.{j + 1}:");
                matrix[i, j] = int.Parse(Console.ReadLine());
            }
        }


        Console.Write(string.Join(" ", SpiralOrder(matrix)));
    }


    public static int[] SpiralOrder(int[,] matrix)
    {
        int rows = matrix.GetLength(0),
            columns = matrix.GetLength(1);


        int[] output = new int[rows * columns];


        bool[,] seen = new bool[rows, columns];
        int[] dr = { 0, 1, 0, -1 };
        int[] dc = { 1, 0, -1, 0 };
        int r = 0, c = 0, di = 0;


        // Iterate from 0 to R * C - 1
        for (int i = 0; i < rows * columns; i++)
        {
            output[i] = (matrix[r, c]);
            seen[r, c] = true;
            int cr = r + dr[di];
            int cc = c + dc[di];


            if (0 <= cr && cr < rows && 0 <= cc && cc < columns
                && !seen[cr, cc])
            {
                r = cr;
                c = cc;
            }
            else
            {
                di = (di + 1) % 4;
                r += dr[di];
                c += dc[di];
            }
        }
        return output;
    }
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS