---
title: "蛇行矩阵问题"
author: "celebration"
date: "2008-07-06T06:50:31Z"
tags: []
slug: "untitled"
draft: false
lastmod: "2008-07-06T06:50:31Z"
id: 211968
url: "https://celebration.iteye.com/blog/211968"
---

Problem  
蛇形矩阵是由1开始的自然数依次排列成的一个矩阵上三角形。

Input  
本题有多组数据，每组数据由一个正整数N组成。（N不大于100）

Output  
对于每一组数据，输出一个N行的蛇形矩阵。两组输出之间不要额外的空行。

矩阵三角中同一行的数字用一个空格分开。行尾不要多余的空格。

Sample Input  
5

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

 

程序如下：

```
public class SnakeMatrix{
	public static void main(String[] args){
		int n = Integer.valueOf(args[0]);
		int[][] arr = new int[n][n];
		int temp = 1;
		for(int i=0;i<n;i++){
			for(int j=0;j<=i;j++){
				arr[i-j][j] = temp++;
			}
		}
		for(int i=0;i<n;i++){
			for(int j=0;j<n-i;j++){
				System.out.print(arr[i][j]+" ");
			}
			System.out.println();
		}
	}
}
```

 

算法分析：

      只要把该矩阵顺时针旋转45度就很容易发现规律了。也就是行号+列号相等的元素在旋转后同一行中，例如（0，4）（1，3）（2，2）（3，1）（4，0）在一行，按照从小到大的顺序排列。