package com.tj.chap4;
import java.util.Scanner;
/**
* **螺旋填数
读入两个整数m,n,输出一个m 行n 列的矩阵,这个矩阵是1~m*n 这些自然
数按照右、下、左、上螺旋填入的结果。
例如:读入4, 5,
则输出
1 2 3 4 5
14 15 16 17 6
13 20 19 18 7
12 11 10 9 8
* */
public class Demo_17 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("请输入一个整数表示行:");
int height = input.nextInt();
System.out.println("请输入一个整数表示列:");
int width = input.nextInt();
int arr[][] = new int[height][width];
todo(arr);
}
public static void todo(int[][] arr){
int m = arr.length;//数组的高度
int n = arr[m-1].length;//数组的宽度
System.out.println("数组高度最大编号为:"+(m-1));
System.out.println("数组宽度最大编号为:"+(n-1));
int[][] dis = {
{0,1},//右
{1,0},//下
{0,-1},//左
{-1,0}//上
};//控制方向
int d= 0;//控制转变方向
int step = 1;//控制每次填写的数
int w = 0;//每次填写时的纵坐标
int h = 0;//每次填写时的横坐标
for(int i = 0;i<m*n;i++){
//System.out.println("填写arr["+w+"]["+h+"]"+"为"+step);
arr[w][h] = step;
step++;
w+=dis[d][0];
h+=dis[d][1];
if(w<m&&h<n&&w>=0&&h>=0&&arr[w][h]==0){
}else{
if(d<3){
d++;
}else{
d=0;
}
//System.out.println("改变方向");
w+=dis[d][0];
h+=dis[d][1];
if(d==1){
h-=1;
}else if(d==3){
h+=1;
}else if(d==2){
w-=1;
}else{
w+=1;
}
}
//System.out.println("下一次填写arr["+w+"]["+h+"]"+"为"+step);
}
for(int[] i :arr){
for(int j :i){
System.out.print(" "+j+" \t");
}
System.out.println();
}
}
}
Java螺旋填数
最新推荐文章于 2024-05-12 16:57:11 发布