Hi,
Need code to traverse through a two dimensional array as follows:
1 2 3 4 5
6 7 8 9 10
11 12 13 14 15
16 17 18 19 20
Required result: 1,2,3,4,5,10,15,20,19,18,17,16,11,6,7,8,9,14,13,12.
Loading
Know the answer? Post it — somebody with the same question will find it here.
Sign in to answer this question
It is the same account you read, post and publish with — and you will come straight back to this page.
Roy SPosted Jul 13, 2010, 12:56 PM
using System;
namespace reverse
{
class Program
{
static void Main(string[] args)
{
int[,] matrix = new int[,] { { 1, 2, 3, 4, 5 }, { 6, 7, 8, 9, 10 }, { 11, 12, 13, 14, 15 }, { 16, 17, 18, 19, 20 } };
int rows = matrix.GetLength(0);
int cols = matrix.GetLength(1);
int r = 0, c = 0;
if (rows < 2 || cols < 2)
foreach (int i in matrix)
Console.WriteLine(i);
else
{
for (int i = 0; i < rows / 2; i++)
{
for (c = i; c < cols - i - 1; c++)
Console.WriteLine(matrix[i, c]);
for (r = i; r < rows - i - 1; r++)
Console.WriteLine(matrix[r, c]);
for (; c > i; c--)
Console.WriteLine(matrix[r, c]);
for (; r > i; r--)
Console.WriteLine(matrix[r, c]);
}
if (rows % 2 != 0)
for (; 2 * c < cols; c++)
Console.WriteLine(matrix[r, c]);
}
Console.ReadLine();
}
}
}
What is done is that one turn around is being repeated a couple of times (depending of the number of rows) and then if the number of rows is odd (there's still a possibility that there's a number in the middle) it displays the middle row.
EDIT: It doesn't work for an array with only one row or column...fixed