OJ-0722

题目

螺旋数字矩阵
题目描述:疫情期间,小明隔离在家,百无聊赖,在纸上写数字玩。
他发明了一种写法:给出数字个数n和行数m (0 小明对这个矩阵有些要求:
1.每行数字的个数一样多
2.列的数量尽可能少
3.填充数字时优先填充外部
4.数字不够时,使用单个*号占位
输入描述:两个整数,空格隔开,依次表示n、m
输出描述:符合要求的唯一矩阵
示例1

输入:
9 4
输出:
1 2 3
* * 4
9 * 5
8 7 6

说明:9个数字写成4行,最少需要3列

示例2

输入:
3 5
输出:
1
2
3
*
*

说明:3个数字写5行,只有一列,数字不够用*号填充

示例3

输入:
120 7
输出:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 19
45 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 63 20
44 83 114 115 116 117 118 119 120 * * * * * * 99 64 21
43 82 113 112 111 110 109 108 107 106 105 104 103 102 101 100 65 22
42 81 80 79 78 77 76 75 74 73 72 71 70 69 68 67 66 23
41 40 39 38 37 36 35 34 33 32 31 30 29 28 27 26 25 24

参考

import java.util.Scanner;
 
public class Main { 
    public static int[] directions = {0, 1, 0, -1, 0};
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int[] params = split(in.nextLine(), " ");
        int k = params[0];  
        int n = params[1];  
 
        String[][] matrix = new String[n][(k - 1) / n + 1];
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < (k - 1) / n + 1; j++) {
                matrix[i][j] = "*";
            }
        }
        
 
        int start_x = 0;
        int start_y = 0;
        int count = 1; 
        int index = 0; 
 
        while (true){
            if(count > k){
                break;
            } else {
                matrix[start_x][start_y] = String.valueOf(count);
                count+=1;
                int new_x = start_x + directions[index];
                int new_y = start_y + directions[index+1];
                
    
                if (new_x < 0 || new_x >= n || new_y < 0 || new_y >= (k - 1) / n +1 
                    || !matrix[new_x][new_y].equals("*")) {
                    index = (index + 1) % 4;
                    start_x = start_x + directions[index];
                    start_y = start_y + directions[index+1];
                } else {
                    start_x= new_x;
                    start_y= new_y;
                }
 
            }
        }
 
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < (k - 1) / n + 1; j++) {
                System.out.print(matrix[i][j]);
                if(j != (k - 1) / n){
                    System.out.print(" ");
                }
            }
            System.out.println();
        }
 
    }
    
    public static int[] split(String input_str,String chars){
        String[] tmp2 = input_str.split(chars);
        int[] counts = new int[tmp2.length];
        for (int i = 0; i < tmp2.length; i++) {  
            counts[i] = Integer.parseInt(tmp2[i]);
        }
        return counts;
    }
}

https://blog.csdn.net/weixin_52908342/article/details/135613211

你可能感兴趣的:(OJ,java,算法)