spiral-matrix I&II

题目来源:Leeicode

Given an integer n, generate a square matrix filled with elements from 1 to n 2 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) {
        if(n<=0)
            return new int[][]{};
        int a[][]=new int[n][n];
        int temp=1;
        int left=0;int top=0;int right=n-1;int bottom=n-1;//关键是定义四个边界条件
        while(left<right&&top<bottom) {
            for (int i = left; i <= right; i++)
                a[top][i] = temp++;
            for (int i = top + 1; i <=bottom; i++)
                a[i][right] = temp++;
            for (int i = right - 1; i >= left; i--)
                a[bottom][i] = temp++;
            for (int i = bottom - 1; i > top; i--)
                a[i][left] = temp++;
            left++;
            right--;
            top++;
            bottom--;}
        
        if (n%2==1)
            a[n/2][n/2]=temp;
        return a;
}
}

II

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].

public List<Integer> spiralOrder(int[][] matrix) {
    List<Integer> ls=new ArrayList<>();
    if (matrix.length==0)
        return ls;
    int rows=matrix.length;
    int cols=matrix[0].length;
    int firstrow=0;int lastrow=rows;int firstcol=0;int lastcol=cols;
    int i=0;
    while (i<(Math.min(rows,cols)+1)/2){
        lastrow=rows-i-1;//每一圈的最后一行
        lastcol=cols-i-1;
        if (i==lastrow)
            for (int j=i;j<=lastcol;j++)
                ls.add(matrix[i][j]);
        else if (i==lastcol)
            for(int j=i;j<=lastrow;j++)
                ls.add(matrix[j][i]);
        else{//每一圈第一行
            for (int j=i;j<=lastcol;j++){
                ls.add(matrix[i][j]);

            }
            //每一圈最后一列
            for (int j=i+1;j<=lastrow;j++)
                ls.add(matrix[j][lastcol]);
            //每一圈最后一行
            for (int j=lastcol-1;j>=i;j--)
                ls.add(matrix[lastrow][j]);
            //每一圈第一列
            for (int j=lastrow-1;j>i;j--)
                ls.add(matrix[j][i]);
        }
        i++;
    }
    return ls;

}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值