/*
* 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 {
private int n = 0;
private int snakeMatrix[][] = new int[n][n];
/*
* 构造函数,用于初始化要打印的N行,以及根据N值初始化蛇形数组。
*/
public SnakeMatrix(int n)
{
this.n = n;
this.snakeMatrix = new int[this.n][this.n];
this.iniSnakeMatrix();
}
/*
* 按照规律初始化蛇形数组
*/
private int[][] iniSnakeMatrix()
{
for(int i = 0; i < this.n; i++)
{
for(int j = 0; j < this.n - i; j++)
{
if ( i == 0)
{
snakeMatrix[i][j] = ((j + 1) * (j + 2))/2;//第一行的规律是(n+1)*(n+2)/2
}
else
{
snakeMatrix[i][j] = snakeMatrix[i - 1][j+1] - 1;//后面的行中数字等于上一行左移1位后再减1
}
}
}
return snakeMatrix;
}
/*
* 打印输出蛇形数组,各数字使用空格分离,并且每行的行尾没有多余的空格
*/
public void printSnakeMatrix()
{
String tmp = null;
for (int i = 0; i < snakeMatrix.length; i++)
{
for (int j = 0; j < snakeMatrix[i].length; j++)
{
tmp = ((j != snakeMatrix.length -i -1) ? " " : "");//行中加空格,行尾不要多余的空格
if (snakeMatrix[i][j] != 0)//去掉数组中的0,即清零
{
System.out.print(snakeMatrix[i][j] + tmp);
}
}
System.out.print("\n");//打完一行后,输出换行符
}
return;
}
/*
* 返回蛇形数组
*/
public int[][] getSnakeMatrix()
{
return this.snakeMatrix;
}
}
分享到:
相关推荐
旅行商问题,TSP问题(Travelling Salesman Problem)规约矩阵法实现,有详细注释,可以使用,结果保存在工程的txt文件中
C#,蛇梯问题(Snake and Ladder Problem)的算法与源代码 蛇梯问题 Snake and Ladder Problem 给定一个蛇梯板,找出从源单元格或第一个单元格到达目标单元格或最后一个单元格所需的最小掷骰次数。基本上,玩家可以...
Wicked Environmental Problem
master page search problem viewdata js
The C10K problem
《Approaching (Almost) Any Machine Learning Problem》
Title: Computer-Based Problem Solving Process Author: Teodor Rus Length: 350 pages Edition: 1 Language: English Publisher: World Scientific Publishing Company Publication Date: 2015-05-30 ISBN-10: ...
MCM 2012年 problem A problem B problem C 枪手论文
Problem solving with C++
8D is a problem-solving methodology for product and process improvement. It is structured into eight disciplines, emphasizing team synergy. The team as whole is better and smarter than the quality sum...
Problem Arrangement zoj 3777
Problem Solving with C++, Global Edition by Walter Savitch (author) (Author) Pages:1117 出版社: Pearson Education Limited; 10th edition edition (November 20, 2017) Language: English ISBN-10: ...
On a problem of formal logic___ramsey___1928On a problem of formal logic___ramsey___1928On a problem of formal logic___ramsey___1928On a problem of formal logic___ramsey___1928On a problem of formal ...
this is the machine problem solution for operating system class
算法设计里关于taxi problem的C语言代码
Java An Introduction to Problem Solving and Programming全英文,第六版,共享给大家,希望有需要的朋友喜欢
java xml realworld problem,java xml 技术 详细说明明
HDOJ Problem 1001 C++版
flow shop problem GA算法 详细代码标注
2SAT problem ppt 教程, 计算机算法导论