
- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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 following until all the inner matrix and the outer matrix are covered −
Step1 − Move elements of top row
Step2 − Move elements of last column
Step3 − Move elements of bottom row
Step4 − Move elements of first column
Step5 − Repeat above steps for inner ring while there is an inner matrix
Example
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); } } }
Output
1 2 3 4 5 6 12 18 17 16 15 14 13 7 8 9 10 11
- Related Questions & Answers
- Print n x n spiral matrix using O(1) extra space in C Program.
- How to rotate a matrix of size n*n to 90 degree using C#?
- How to rotate a matrix of size n*n to 90-degree k times using C#?
- Program to print matrix elements in spiral order in python
- Print Matrix in spiral way
- Print a given matrix in reverse spiral form in C++
- Python program to print a checkboard pattern of n*n using numpy.
- Construct an identity matrix of order n in JavaScript
- Print a given matrix in counter-clockwise spiral form in C++
- Matrix creation of n*n in Python
- Spiral Matrix in C++
- Java program to print a given matrix in Spiral Form.
- Count frequency of k in a matrix of size n where matrix(i, j) = i+j in C++
- Queries to Print All the Divisors of n using C++
- Python program to print check board pattern of n*n using numpy
Advertisements