AcWing0756. 蛇形矩阵

  1. 题目

    输入两个整数n和m,输出一个n行m列的矩阵,将数字 1 到 n*m 按照回字蛇形填充至矩阵中。

    具体矩阵形式可参考样例。

  2. 输入格式

    输入共一行,包含两个整数n和m。

  3. 输出格式

    输出满足要求的矩阵。

    矩阵占n行,每行包含m个空格隔开的整数。

  4. 数据范围

    1≤n,m≤100

  5. 输入样例

    3 3
    
  6. 输出样例

    1 2 3
    8 9 4
    7 6 5
    
  7. 代码1

    import java.io.*;
    import java.util.*;
    
    public class Main {
        public static void main(String[] args) {
            Scanner sc = new Scanner(System.in);
            int m = sc.nextInt();
            int n = sc.nextInt();
            int[][] res = new int[m][n];
    
            int left = 0, right = n - 1, top = 0, bottom = m - 1;
            int num = 1;
    
            while(num <= m * n) {
                for(int i = left; i <= right && num <= m * n; i++) {
                    res[top][i] = num++;
                }
                top++;
                for(int i = top; i <= bottom && num <= m * n; i++) {
                    res[i][right] = num++;
                }
                right--;
                for(int i = right; i >= left && num <= m * n; i--) {
                    res[bottom][i] = num++;
                }
                bottom--;
                for(int i = bottom; i >= top && num <= m * n; i--) {
                    res[i][left] = num++;
                }
                left++;
            }
    
            for(int i = 0; i < m; i++) {
                for(int j = 0; j < n; j++) {
                    System.out.print(res[i][j] + " ");
                }
                System.out.println();
            }
    
    
        }
    }
    
  8. 代码2

    import java.util.*;
    import java.io.*;
    
    public class Main {
        public static void main(String[] args) {
            Scanner sc = new Scanner(System.in);
            int row = sc.nextInt();
            int col = sc.nextInt();
    
            int res[][] = new int[row][col];
            int[] dx = new int[]{-1, 0, 1, 0};
            int[] dy = new int[]{0, 1, 0, -1};
            int x = 0, y = 0, d = 1;
            for(int num =1; num <= row * col; num++) {
                res[x][y] = num;
                int next_x = x + dx[d];
                int next_y = y + dy[d];
                if(next_x < 0 || next_x >= row || next_y < 0 || next_y >= col || res[next_x][next_y] != 0) {
                    d = (d + 1) % 4;
                    next_x = x + dx[d];
                    next_y = y + dy[d];
                }
                x = next_x;
                y = next_y;
            }
    
            for(int i = 0; i < row; i++) {
                for(int j = 0; j < col; j++) {
                    System.out.print(res[i][j] + " ");
                }
                System.out.println();
            }
        }
    }
    
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值