How to print a given matrix in spiral form with C#

1 Answer

0 votes
using System;

public class Program
{
	private static void PrintMatrixInSpiralForm(int[][] matrix)
	{
		if (matrix == null || matrix.Length == 0) {
			return;
		}

		int top = 0, bottom = matrix.Length - 1;
		int left = 0, right = matrix[0].Length - 1;

		while (true) {
			if (left > right) {
				break;
			}

			// top row
			for (int i = left; i <= right; i++) {
				Console.Write(matrix[top][i] + " ");
			}
			Console.Write("\n");
			top++; // next row

			if (top > bottom) {
				break;
			}

			// right column
			for (int i = top; i <= bottom; i++) {
				Console.Write(matrix[i][right] + " ");
			}
			Console.Write("\n");
			right--; // previous column

			if (left > right) {
				break;
			}

			// bottom row
			for (int i = right; i >= left; i--) {
				Console.Write(matrix[bottom][i] + " ");
			}
			Console.Write("\n");
			bottom--; // previous row

			if (top > bottom) {
				break;
			}

			// left column
			for (int i = bottom; i >= top; i--) {
				Console.Write(matrix[i][left] + " ");
			}
			Console.Write("\n");
			left++; // next column
		}
	}
	public static void Main(string[] args)
	{
		  int[][] matrix = new int[][]
		  {
			  new int[] {1, 2, 3, 4},
			  new int[] {5, 6, 7, 8},
			  new int[] {9, 10, 11, 12},
			  new int[] {13, 14, 15, 16}
		  };

		PrintMatrixInSpiralForm(matrix);
	}
}






/*
run:
  
1 2 3 4 
8 12 16 
15 14 13 
9 5 
6 7 
11 
10 
  
*/

 



answered Sep 13, 2022 by avibootz
...