Spiral Matrix I && Spiral Matrix II

問題I描述

Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order.

For example,
Given the following matrix:

[
[ 1, 2, 3 ],
[ 4, 5, 6 ],
[ 7, 8, 9 ]
]
You should return [1,2,3,6,9,8,7,4,5].

思考:從左到右,然後從上到下,然後從右到左,然後從下到上,一次循環。注意邊界問題

方法

  • 設置左右邊界colStart, colEnd,上下邊界rowStart,rowEnd.
  • 左到右之後 rowStart + 1 上到下之後,colEnd - 1;如果rowStart <= rowEnd,則進行從右到左,並且rowEnd - 1;如果colStart <= colEnd,則從下到上,並且colStart - 1;直到不滿足條件(rowStart <= rowEnd && colStart <= colEnd)

代碼

public class Solution {
    public List<Integer> spiralOrder(int[][] matrix) {
        List<Integer> re =  new ArrayList<Integer>();
        int rowStart = 0;         
        int rowEnd = matrix.length - 1;
        if(rowEnd == -1)
            return re;
        int colStart = 0;
        int colEnd = matrix[0].length - 1;
        while(rowStart <= rowEnd && colStart <= colEnd){
            //left to right
            for(int i = colStart; i <= colEnd; i++)
                re.add(matrix[rowStart][i]);
            rowStart++;

            // up to down
            for(int j = rowStart; j <= rowEnd; j++)
                re.add(matrix[j][colEnd]);
            colEnd--;

            //right to left
            if(rowStart <= rowEnd){
                for(int i = colEnd; i >= colStart; i--)
                    re.add(matrix[rowEnd][i]);
            }
            rowEnd--;

            // down to up
            if(colStart <= colEnd ){
                for(int j = rowEnd; j >= rowStart; j--)
                    re.add(matrix[j][colStart]);
            }
            colStart++; 
        }
        return re;
    }
}

問題II描述

Given an integer n, generate a square matrix filled with elements from 1 to n2 in spiral order.

For example,
Given n = 3,

You should return the following matrix:
[
[ 1, 2, 3 ],
[ 8, 9, 4 ],
[ 7, 6, 5 ]
]

思考:類似問題一

代碼

public class Solution {
    public int[][] generateMatrix(int n) {
        int[][] matrix = new int[n][n];
        int num = 1;
        int i = 0;
        while(num <= n * n){   
            int j = i;

            // left to right
            for(; j < n - i; j++)
                matrix[i][j] = num++;

            // up to down
            for(j = i + 1; j < n - i; j++)
                matrix[j][n - i - 1] = num++;

            //right to left
            for(j = n - i - 2; j >= i; j--)
                matrix[n - i - 1][j] = num++;

            //down to up
            for(j = n - i - 2; j > i; j--)
                matrix[j][i] = num++;
            i++;
        }
        return matrix;
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章