问题描述
输入两个整数m,n 输出1-m每个数字按顺时针螺旋且行数等于n的矩阵 数字不足部分用*补足
示例:
输入:3,5
输出:
1
2
3
*
*
输入:9,4
输出:
1 2 3
* * 4
9 * 5
8 7 6
代码
package com;
import java.util.Scanner;
public class Main1 {
//case中需要使用final修饰的静态属性
//输入两个整数m,n 输出1-m每个数字按顺时针螺旋且行数等于n的矩阵 数字不足部分用*补足
//方向常量
public static final int RIGHT = 0 ;
public static final int DOWN = 1 ;
public static final int LEFT = 2 ;
public static final int UP = 3 ;
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
//数字
int n = in.nextInt();
//矩阵行数
int line = in.nextInt();
//确定矩阵列数
int col = n % line == 0 ? n/line : n/line+1;
outPut(line,col,n);
}
//输出line * col 的矩阵,最大数字为num
public static void outPut(int line , int col ,int num){
//二维数组存储结果
int[][] res = new int [line][col];
//默认方向为右
int to = RIGHT ;
//初始位置为 x,y
int x = 0 ;
int y = 0 ;
//当前需要填充的数字
int cur = 1;
while(cur <= num){
// System.out.println("x="+x+" y="+y);
res[x][y] = cur;
//确定下一步的方向
to = confirmTo(res,x,y,line,col,to);
switch(to){
case RIGHT:
y++;
break;
case DOWN:
x++;
break;
case LEFT:
y--;
break;
case UP:
x--;
break;
default:
}
cur++;
}
for(int i = 0 ; i < line ; i++){
for(int j = 0 ; j < col ; j++){
if(res[i][j] != 0 ){
System.out.print(res[i][j]+"\t");
}else{
System.out.print("*" +"\t");
}
}
System.out.println();
}
}
//矩阵n*m 坐标x,y 当前方向to array回旋矩阵
public static int confirmTo(int[][] array , int x , int y , int n , int m ,int to ){
//根据当前方向及当前坐标位置确定下一步的方向
//数组初始化为0 若下一位置值不为0 说明已经走过
int res = to;
if(to == RIGHT &&(y == m-1 || array[x][y+1] != 0 )){
res = DOWN;
}else if(to == DOWN && (x == n-1 || array[x+1][y]!=0 )){
res = LEFT;
}else if( to == LEFT && (y == 0 || array[x][y-1] != 0 )){
res = UP;
}else if(to == UP &&(x == 0 || array[x-1][y] != 0 )){
res = RIGHT;
}
return res ;
}
}