Output a m * n matrix in the following regular order: line1: 1 6 7 line2: 2 5 8 line3: 3 4 9

Source: Internet
Author: User

Output an M * n matrix arranged according to the following rules.
1 6 7
2 5 8
3 4 9

 

Analysis: The key is to find out the matrix rules. on the Internet, the analysis is as follows:

 

Set behavior I, column J

 

 

1 2 M 2 m + 1 4 M 4 m + 1 6 m ..

2 m + M-1 2 m + 2 4s-1 4 m + 2 6s-1 ..

3

........

........

M m + 1 2 m + M 3 m + 1 4 m + M 5 m + 1 ..

 

 

We can see that the values of the matrix (I, j) are regular:

(1) when it is an even Column

 

(J, j) = J * M-I + 1;

 

(2) when it is a base series:

 

(J, j) = (J-1) * m + I;

 

 

With this rule, the algorithm is simple. The C # implementation is as follows:

 

 

Using system;
Using system. Collections. Generic;
Using system. LINQ;
Using system. text;

Namespace first_matix
{
Class Program
{
Static void main (string [] ARGs)
{
Printmatrix (3, 3 );
Console. readkey ();

}

Static void printmatrix (int m, int N)
{

For (INT I = 1; I <= m; I ++)
{

For (Int J = 1; j <= N; j ++)
{
If (J % 2 = 0)
Console. Write ("{0}", J * M-I + 1 );
Else
Console. Write ("{0}", (J-1) * m + I );

 
}

Console. writeline ();
}
 

}
}
}

 

 

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.