A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© 佐佑 中级黑马   /  2015-3-26 23:23  /  460 人查看  /  3 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

1      2    3   4    5
22   23  24 25   6
21   20  19 18   7
14   15  16 17   8
13   12  11  10  9

螺旋的图形,有谁会的吗

3 个回复

倒序浏览
public class test
{
  public static void main(String arg[])
{
  System.out.println("打印螺旋数组如下: ");
        Scanner input = new Scanner(System.in);
        int aa = input.nextInt();
        int jj = aa;
        test ra=new test();
        int[][] array=new int[aa][jj];
        for(int _row=0;_row<aa;_row++){
            for(int _col=0;_col<jj;_col++){
                array[_row][_col]=-1;
            }
        }
        ra.printRatateArray(array);
}
public void printRatateArray(int[][] array){
        //数组行数,列数
        int rows=array.length;
        int cols=array[0].length;
        //矩形的数量,将一条线也视为上下边重合的矩形
        int regCount=rows%2==0?rows/2:(rows+1)/2;
        //初始种子数,即最外层矩形的左上角值
        int seedNum=1;
        for(int i=0;i<regCount;i++){
            System.out.println("种子数据:"+seedNum);
            //遍历数组,填充数据
            for(int _row=0;_row<rows;_row++){
                for(int _col=0;_col<cols;_col++){
                    //矩形上边横线
                    if(_row==i&&array[_row][_col]==-1){
                        array[_row][_col]=seedNum+_col-i;
                    }
                    //矩形右边竖线
                    if(_col==(cols-i-1)&&array[_row][_col]==-1){
                        array[_row][_col]=seedNum+(rows-2*i)+(cols-2*i)-2-(rows-i-1-_row);
                    }
                    //矩形下边横线
                    if(_row==(rows-1-i)&&array[_row][_col]==-1){
                        array[_row][_col]=seedNum+(rows-2*i)+(cols-2*i)-2+(cols-i-1-_col);
                    }
                    //矩形左边竖线
                    if(_col==i&&array[_row][_col]==-1){
                        array[_row][_col]=seedNum+(rows-2*i)+(cols-2*i)-2+(cols-i*2)-1+(rows-i-1-_row);
                    }
                }
            }
            seedNum=(rows-2*i+cols-2*i)*2-4+seedNum;
        }
        //打印结果
        for(int _row=0;_row<rows;_row++){
            for(int _col=0;_col<cols;_col++){
                System.out.printf("%3d",array[_row][_col]);//用了java5的格式化输出,故该程序要在jdk5下编译
            }
            System.out.println();
        }
    }



}
回复 使用道具 举报
有大神!
回复 使用道具 举报
有大神!围观。。。【数字君】
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马