Leetcode#59 Spiral Matrix II

public class Solution {
    public int[][] generateMatrix(int n) {
        int right=0,down=0,left=0,up=0;
        int[][] res = new int[n][n];
        int cnt=1;
        while(true){
            for(int i=right;i

生成旋转矩阵,关键在于四个方向的过程,遵循右-下-左-上,四个步骤,同时注意break的条件。

leetcode 54 Spiral Matrix#

public class Solution {
    public List spiralOrder(int[][] matrix) {
        int row = matrix.length; // row是行数, col是列数
        List res = new LinkedList<>();
        if(row==0) return res;
        int col = matrix[0].length;
        int right=0,down=0,left=0,up=0;
        while (true) {
            for (int i = right; i < col-left; i++) {
                res.add(matrix[down][i]);
            }
            down++;
            if(down+up==row) break;
            for (int i = down; i < row-up; i++) {
                res.add(matrix[i][col-left-1]);
            }
            left++;
            if(left+right==col) break;
            for(int i=left;i

类似的题目,就是遵从四个方向的步骤,然后注意break的条件。

你可能感兴趣的:(Leetcode#59 Spiral Matrix II)