My Java Solution Logic thinking


  • 0
    H

    思路:

    1. 把矩阵看作若干个顺时针方向的圈组成,用一个循环来打印每个圈。
    2. 每个圈的左上角行列号相等,设为(start, start)作为圈的起点。
    3. 如何打印一个圈:左到右,上到下,右到左,下到上。(添加前提条件。)

    ····

     public class Solution {
    public List<Integer> spiralOrder(int[][] matrix) {
        List<Integer> list = new ArrayList<>();
        if (matrix == null  || matrix.length == 0) return list;
        int rows = matrix.length;
        int columns = matrix[0].length;
        int start = 0;
        while (columns > start * 2 && rows > start * 2)
        {
            list = PrintMatixCircle(matrix, list, columns, rows, start);
            start++;
        }
        return list;
    }
    
    public List<Integer> PrintMatixCircle(int[][] matrix, List<Integer> list, int columns, int rows, int start){
        int endcolumn = columns - 1 - start;
        int endrow = rows - 1 - start;
        int i = 0;
        //从左到右打印一行
        for (i = start ;i <= endcolumn;i++)
            list.add(matrix[start][i]);
        if (start < endrow) 
            //从上到下打印一列
            for (i = start + 1; i <= endrow; i++) 
                list.add(matrix[i][endcolumn]);
        if (start < endrow && start < endcolumn) 
            //从右到左打印一行
            for (i = endcolumn - 1; i >= start; i--) 
                list.add(matrix[endrow][i]);
        if (endrow - start >= 2 && endcolumn > start) 
            //从下到上打印一列
            for (i = endrow - 1; i > start; i--) 
                list.add(matrix[i][start]);
        return list;
    }
    

    }
    ····


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.