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;
}
}
蛇形输出、螺旋输出
最新推荐文章于 2024-07-02 18:06:22 发布