How to print a matrix of size n*n in spiral order using C#?

PHPz
Release: 2023-08-23 13:17:02
forward
1054 people have browsed it

How to print a matrix of size n*n in spiral order using C#?

To rotate a matrix in spiral order, we need to do the following until all inner and outer matrices are covered:

  • Step 1 - Move the elements in the top row

  • Step 2 - Move the elements in the last column

  • Step 3 - Move the elements in the bottom row

  • Step 4 - Move the elements in the first column

  • Step 5 - Repeat the above steps with the inner matrix present

Example

Demonstration

using System;
namespace ConsoleApplication{
   public class Matrix{
      public void PrintMatrixInSpiralOrder(int m, int n, int[,] a){
         int i, k = 0, l = 0;
         while (k < m && l < n){
            for (i = l; i < n; ++i){
               Console.Write(a[k, i] + " ");
            }
            k++;
            for (i = k; i < m; ++i){
               Console.Write(a[i, n - 1] + " ");
            }
            n--;
            if (k < m){
               for (i = n - 1; i >= l; --i){
                  Console.Write(a[m - 1, i] + " ");
               }
               m--;
            }
            if (l < n){
               for (i = m - 1; i >= k; --i){
                  Console.Write(a[i, l] + " ");
               }
               l++;
            }
         }
      }
   }
   class Program{
      static void Main(string[] args){
         Matrix m = new Matrix();
         int R = 3;
         int C = 6;
         int[,] aa = { { 1, 2, 3, 4, 5, 6 },
            { 7, 8, 9, 10, 11, 12 },
            { 13, 14, 15, 16, 17, 18 } };
            m.PrintMatrixInSpiralOrder(R, C, aa);
      }
   }
}
Copy after login

Output

1 2 3 4 5 6 12 18 17 16 15 14 13 7 8 9 10 11
Copy after login

The above is the detailed content of How to print a matrix of size n*n in spiral order using C#?. For more information, please follow other related articles on the PHP Chinese website!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template