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
from System import *
from System.Collections.Generic import *
from System.Linq import *
class Program(object):
def __init__(self):
self._res = List[int]()
def Main(args):
row = 4
col = 4
matrix = Array[int]((, , , ))
lstStr = List[str]()
Program.RowConstantColVary(0, 3, matrix)
Program.ColConstantRowVary(3, 3, matrix)
Program.RowConstantColVaryReverse(3, 2, matrix)
Program.ColConstantRowVaryReverse(2, 0, matrix)
Program.RowConstantColVary(1, 2, matrix)
Program.RowConstantColVaryReverse(2, 2, matrix)
self._res.Take((row * col)).ToList().ForEach()
Console.ReadKey()
Main = staticmethod(Main)
def RowConstantColVary(startRow, endCol, matrix):
j = startRow
while j <= endCol:
self._res.Add(matrix[startRow][j])
j += 1
RowConstantColVary = staticmethod(RowConstantColVary)
def ColConstantRowVary(endRow, startCol, matrix):
i = 1
while i <= endRow:
self._res.Add(matrix[i][startCol])
i += 1
ColConstantRowVary = staticmethod(ColConstantRowVary)
def RowConstantColVaryReverse(startRow, endCol, matrix):
j = endCol
while j >= 0:
self._res.Add(matrix[startRow][j])
j -= 1
RowConstantColVaryReverse = staticmethod(RowConstantColVaryReverse)
def ColConstantRowVaryReverse(endRow, startCol, matrix):
i = endRow
while i >= endRow - 1:
self._res.Add(matrix[i][startCol])
i -= 1
ColConstantRowVaryReverse = staticmethod(ColConstantRowVaryReverse)