`
1140566087
  • 浏览: 547498 次
  • 性别: Icon_minigender_1
  • 来自: 武汉
博客专栏
2c4ae07c-10c2-3bb0-a106-d91fe0a10f37
c/c++ 入门笔记
浏览量:18072
3161ba8d-c410-3ef9-871c-3e48524c5263
Android 学习笔记
浏览量:309404
Group-logo
J2ME 基础学习课程集
浏览量:17984
A98a97d4-eb03-3faf-af96-c7c28f709feb
Spring 学习过程记录...
浏览量:17192
社区版块
存档分类
最新评论

方正的主对角线为:“上三角”

阅读更多
import java.util.Scanner;


// 题目:
//方阵的主对角线之上称为“上三角”。
//请你设计一个用于填充n阶方阵的上三角区域的程序。
//填充的规则是:使用1,2,3….的自然数列,从左上角开始,按照顺时针方向螺旋填充。
//例如:当n=3时,输出:
//1 2 3
//6 4
//5
//当n=4时,输出:
//1  2 3 4
//9 10 5
//8  6
//7
//当n=5时,输出:
//  1  2  3  4  5
// 12 13 14  6 
// 11 15  7
// 10  8
//  9

// 思路:
/*	n = 5  的时候,能到的最大的长度为:(n*n-n)/2+n
 * 使用二维数组保存矩阵中的数值
 * 先向右,然后下左,然后向上,依次循环
 */
public class 上三角 {
	public static void main(String[] args){
		Scanner input = new Scanner(System.in);
		System.out.print("请输入一个数:");
		int n = Integer.parseInt(input.next());
		f(n);

	}
	public static void f(int h){
		//
		int n = h;	//n 的值 n行n 列
		int[][] array = new int[n][n];
		int temp = 1;
		int x=0,y = 0;
		array[x][y] = temp;	//进行元素的添加
		while(temp<(n*n-n)/2+n){  // n行n列 , 能回到的最大值;
			while(y+1<n && array[x][y+1]==0){	//向右
				array[x][++y] = ++temp;		
			}
			while(x+1<n && array[x+1][y-1]==0){	//向左下
				array[++x][--y] =++temp;
			}
			while(x-1>=0 && array[x-1][y]==0){	//向上
				array[--x][y] = ++temp;
			}
		}
		for(int i=0;i<n;i++){
			for(int j=0;j<n;j++){
				if(array[i][j]!=0){
					System.out.print(array[i][j]+" ");
				}
			}
			System.out.println();
		}
	}
}
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics