题解 | #单链表的排序#

顺时针打印数字矩阵

http://www.nowcoder.com/practice/ce0c22a435114108bd9acc75f81b5802

注意避坑:
代码里面:当读到M=-1,N=-1时,输入终止;
如果使用sc.close就无法通过;但是换用break就可以ac!!!
自己也不清楚为什么,这块折腾了好长时间,因此,在此特意提醒。

import java.util.Scanner;

/**
 * @program: Leetcode
 * @Author: X.Q.X
 * @Date: 2021-08-04 09:52
 */
public class Main {

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        while (sc.hasNext()) {
            String[] tmp = sc.nextLine().split(" ");
            int m = Integer.parseInt(tmp[0]);
            int n = Integer.parseInt(tmp[1]);

            //注意避坑:这里如果使用sc.close就无法通过;但是换用break就可以ac!!!
            if (m == -1 && n == -1) break;

            int[][] matrix = new int[m][n];
            for(int i = 0; i < m; i++) {
                String[] temp = sc.nextLine().trim().split(" ");
                for(int j = 0; j < n; j++)
                    matrix[i][j] = Integer.parseInt(temp[j]);
            }

//            System.out.println(Arrays.toString(matrix[0]));
//            System.out.println(Arrays.toString(matrix[1]));
//            System.out.println(Arrays.toString(matrix[2]));

            System.out.println(spiralOrder(matrix));
        }
    }

    //方法一:递归 + 模拟(按层模拟递归)
    private static String spiralOrder(int[][] matrix) {
        if (matrix == null || matrix.length == 0 || matrix[0].length == 0) return "";

        int m = matrix.length, n = matrix[0].length;
        int[] res = new int[m * n];

        int index = 0;
        int left = 0, right = n - 1, top = 0, bottom = m - 1;
        while (left <= right && top <= bottom) {
            for (int col = left; col <= right; col++) {
                res[index++] = matrix[top][col];
            }

            for (int row = top + 1; row <= bottom; row++) {
                res[index++] = matrix[row][right];
            }

            if (left < right && top < bottom) {
                for (int col = right - 1; col > left; col--) {
                    res[index++] = matrix[bottom][col];
                }

                for (int row = bottom; row > top; row--) {
                    res[index++] = matrix[row][left];
                }
            }
            left++;
            top++;
            right--;
            bottom--;
        }

        StringBuilder ret = new StringBuilder();
        for (int i = 0; i < res.length - 1; i++) {
            ret.append(res[i]).append(",");
        }
        ret.append(res[res.length - 1]);
        return ret.toString();
    }
}
全部评论

相关推荐

jack_miller:我给我们导员说我不在这里转正,可能没三方签了。导员说没事学校催的时候帮我想办法应付一下
点赞 评论 收藏
分享
评论
点赞
收藏
分享
牛客网
牛客企业服务