zoukankan      html  css  js  c++  java
  • [leedcode 59] Spiral Matrix 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 {
        int res[][];
        int val=1;
        public int[][] generateMatrix(int n) {
            //主要是通过画图,判断每个分支的范围,本题还适应非方阵
             res=new int[n][n];
            int minRow=0;
            int maxRow=n-1;
            int minCol=0;
            int maxCol=n-1;
            int val=1;
            while(minRow<=maxRow&&minCol<=maxCol){
                generate(minRow,maxRow,minCol,maxCol);
                minRow++;
                maxRow--;
                minCol++;
                maxCol--;
            }
            return res;
        }
        public void generate(int minRow,int maxRow,int minCol,int maxCol){
            for(int i=minCol;i<=maxCol;i++){
                res[minRow][i]=val++;
            }
            for(int i=minRow+1;i<=maxRow;i++){
                res[i][maxCol]=val++;
            }
            for(int i=maxCol-1;i>=minCol;i--){
                res[maxRow][i]=val++;
            }
            for(int i=maxRow-1;i>minRow;i--){
                res[i][minCol]=val++;
            }
            
        }
    }
  • 相关阅读:
    洛谷1069 细胞分裂
    洛谷1050 循环
    CF Good Bye 2018
    洛谷1043 数字游戏
    洛谷1041 传染病控制
    洛谷1040 加分二叉树
    洛谷1039 侦探推理
    洛谷1038 神经网络
    设计模式的区别
    volatile和synchronized与lock的理解
  • 原文地址:https://www.cnblogs.com/qiaomu/p/4642303.html
Copyright © 2011-2022 走看看