蛇形输出、螺旋输出

package cn.hncu.acm;

import java.util.ArrayList;
import java.util.List;

public class SnackPrint {
    public static void main(String[] args) {
        int[][] num=printSnack(5,5);//蛇形输错0-25
        System.out.println(printSnack(num));//螺旋打印
    }


    private static List<Integer> printSnack(int[][] num) {
        ArrayList<Integer> list=new ArrayList<Integer>();
        int rowLen=num.length;
        int colLen=num[0].length;
        int i = 0;
        int j = 0;
        int temp[][]=new int[rowLen][colLen];
        while(!isFinish(temp)){
            while(j<colLen&&temp[i][j]==0){
                list.add(num[i][j]);
                temp[i][j]=1;
                j++;
            }
            j--;
            i++;
            while(i<rowLen&&temp[i][j]==0){
                list.add(num[i][j]);
                temp[i][j]=1;
                i++;
            }
            i--;
            j--;
            while(j>=0&&temp[i][j]==0){
                list.add(num[i][j]);
                temp[i][j]=1;
                j--;
            }
            j++;
            i--;
            while(i>=0&&temp[i][j]==0){
                list.add(num[i][j]);
                temp[i][j]=1;
                i--;
            }
            j++;
            i++;
        }
        return list;

    }

     /*
    数组全部遍历完成则返回true,还有没访问的返回false
 */
    private static boolean isFinish(int[][] temp) {
        for(int i[]:temp){
            for(int j:i){
                if(j==0)
                    return false;
            }
        }
        return true;
    }


    public static int[][]  printSnack(int weight, int height){
        int x=0;int y=0;
        int[][] num=new int[weight][height];
        int k=num[x][y]=1;
        while(k<height*weight){
            while (y+1<weight&&num[x][y+1]==0) {//向右移动
                y++;
                num[x][y]=++k;
            }
            while (x+1<height&&num[x+1][y]==0) {//向下移动
                x++;
                num[x][y]=++k;
            }
            while (y-1>=0&&num[x][y-1]==0) {//向左移动
                y--;
                num[x][y]=++k;
            }
            while (x-1>=0&&num[x-1][y]==0) {//向上移动
                x--;
                num[x][y]=++k;
            }
        }
        for(int[] i:num){
            for(int j:i){
                System.out.print(j+"\t");
            }
            System.out.println();
        }
        return num;
    }


}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值