[Original] An array integer surround Algorithm

Source: Internet
Author: User

Today, I saw an interview question that a netizen encountered. I thought it was quite interesting. I wrote the algorithm:

Question: print the following matrix

1 2 3 4 5 6

20 21 22 23 24 7

19 32 33 34 25 8

18 31 36 35 26 9

17 30 29 28 27 10

16 15 14 13 12 11

The Code is as follows:

Class program
{
Static void Main (string [] args)
{
New program (). Run ();
}

 

// Number of times in each direction

Int right = 1;
Int down = 0;
Int left = 0;
Int up = 0;

Int n = 6; // matrix N * N

// Matrix rows and columns

Int row = 0;
Int col = 0;

Direction direction = Direction. Right;
Int [,] a = new int [6, 6];

Enum Direction
{
Right = 0,
Down = 1,
Left = 2,
Up = 3
}

Void Run ()
{
For (int I = 1; I <= n * n; I ++)
{
A [row, col] = I;
Fang ();
}

 

For (int I = 0; I <6; I ++)
{
For (int j = 0; j <6; j ++)
{
Console. Write ("{0}", a [I, j]);
}

Console. Write ("\ n ");
}

Console. Read ();
}

 

Void Fang ()
{
Switch (direction)
{
Case Direction. Right:
If (col <n-down-1)
{
Col ++;
}
Else
{
Direction = Direction. Down;
Row ++;
Down ++;
}
Break;
Case Direction. Down:
If (row <n-left-1)
{
Row ++;
}
Else
{
Direction = Direction. Left;
Col --;
Left ++;
}
Break;
Case Direction. Left:
If (col> up)
{
Col --;
}
Else
{
Direction = Direction. Up;
Up ++;
Row --;
}
Break;
Case Direction. Up:
If (row> right)
{
Row --;
}
Else
{
Direction = Direction. Right;
Right ++;
Col ++;
}
Break;
}
}
}

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.