Spiral Matrix I && Spiral Matrix II

来源:互联网 发布:tensorflow官网下载 编辑:程序博客网 时间:2024/05/21 17:33

问题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;    }}
0 0
原创粉丝点击