C# program to traverse a matrix in Spiral Form

Rajnilari2015
Posted by Rajnilari2015 under C# category on | Points: 40 | Views : 2692
Let's say we have a 4*4 matrix with the elements as

{1,2,3,4}
{5,6,7,8}
{9,10,11,12}
{13,14,15,16}


The objective is to visit this matrix in spiral manner such that the output will be

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


The below code will do so

using System;
using System.Collections.Generic;
using System.Linq;

namespace ConsoleApplication2
{
class Program
{
static List<int> res = new List<int>();

static void Main(string[] args)
{
int row = 4;
int col = 4;
int[,] matrix = new int[4, 4] {
{1,2,3,4},
{5,6,7,8},
{9,10,11,12},
{13,14,15,16}
};

List<string> lstStr = new List<string>();

RowConstantColVary(0, 3, matrix);
ColConstantRowVary(3, 3, matrix);
RowConstantColVaryReverse(3, 2, matrix);
ColConstantRowVaryReverse(2, 0, matrix);
RowConstantColVary(1, 2, matrix);
RowConstantColVaryReverse(2, 2, matrix);

res.Take((row * col)).ToList().ForEach(i => Console.Write(i + " "));

Console.ReadKey();

}

private static void RowConstantColVary(int startRow, int endCol, int[,] matrix)
{
for (int j = startRow; j <= endCol; j++)
{
res.Add(matrix[startRow, j]);
}

}
private static void ColConstantRowVary(int endRow, int startCol, int[,] matrix)
{
for (int i = 1; i <= endRow; i++)
{
res.Add(matrix[i, startCol]);
}

}
private static void RowConstantColVaryReverse(int startRow, int endCol, int[,] matrix)
{
for (int j = endCol; j >=0; j--)
{
res.Add(matrix[startRow, j]);
}

}

private static void ColConstantRowVaryReverse(int endRow, int startCol, int[,] matrix)
{
for (int i = endRow; i >= endRow-1; i--)
{
res.Add(matrix[i, startCol]);
}

}
}
}

Comments or Responses

Login to post response