1. 程式人生 > >蛇形輸出、螺旋輸出

蛇形輸出、螺旋輸出

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; } }