首页 > 其他 > 详细

三角螺旋矩阵

时间:2015-03-27 17:37:45      阅读:245      评论:0      收藏:0      [点我收藏+]

题目描述:

方阵的主对角线之上称为“上三角”。


请你设计一个用于填充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(3~20)
程序输出
package string_pracitice;

import java.util.Scanner;

public class SpiralDemo3 {
	public static void main(String[] args) {
		new SpiralDemo3().run();
	}
	public void run(){
		Scanner in = new Scanner(System.in);
       int n = in.nextInt();
       int value[][] = new int[n][n];
      
       int direction = 1; // 1向右,0向左下,2向上
       int x=0;
       int y=0;
       for(int i=0;i<((1+n)*n)/2;i++){
    	   if(value[y][x]==0){
    		   value[y][x]=i+1;
    		   if(direction==1){//向右
    			   if(x+1<n&&value[y][x+1]==0){
    				   x++;
    			   }else{
    				   direction=0;
    				   x--;
    				   y++;
    			   }
    		   }else if(direction==0){//向左下
    			   if(y+1<n&&x-1>=0&&value[y+1][x-1]==0){
    				   x--;
    				   y++;
    			   }else{
    				   direction=2;//向上
    				   y--;
    			   }
    		   }else{//向上
    			   if(y-1>=0&&value[y-1][x]==0){
    				   y--;
    			   }else{
    				   direction=1;
    				   x++;
    			   }
    		   }
    	   }
       }
       for(int i=0;i<n;i++){
    	   for(int j=0;j<n-i;j++){
    		   if(j == 0)
                   System.out.print(value[i][j]);
               else{
                   System.out.print(" "+value[i][j]);
               }
    	   }
    	   System.out.println();
       }
	}
}

:方阵的上三角部分。

要求格式:每个数据宽度为4,右对齐。


三角螺旋矩阵

原文:http://blog.csdn.net/u014010769/article/details/44676653

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!