【Leetcode】之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 ]
]

二.我的解题思路

这道题和之前的spiral matrix I的解法差不多,这道题还要更容易些,直接采用递归的算法思想就能很好的解决本题。测试通过的程序如下:

class Solution {
public:
    vector<vector<int>> generateMatrix(int n) {
        vector<vector<int>> res;
        if(n==0) return res;
        vector<int> tmp(n,0);
        for(int i=0;i<n;i++)
            res.push_back(tmp);
        int curr=1;
        int row_st=0;int row_end=n-1;
        int line_st=0;int line_end=n-1;
        gen_res(res,curr,row_st,row_end,line_st,line_end);
        return res;
        
    }
    
    void  gen_res( vector<vector<int>> &res,int curr,int row_st,int row_end,int line_st,int line_end){
        if(row_st>row_end || line_st>line_end)
            return;
        if(row_st==row_end){
            res[row_st][line_st]=curr;
            return;
        }
         for(int i=line_st;i<=line_end;i++)
            {res[row_st][i]=curr;curr++;}
         for(int i=row_st+1;i<=row_end;i++)
            {res[i][line_end]=curr;curr++;}
         for(int i=line_end-1;i>line_st;i--)
            {res[row_end][i]=curr;curr++;}
         for(int i=row_end;i>row_st;i--)
            {res[i][line_st]=curr;curr++;}
      
    
        row_st++;line_st++;
        row_end--;line_end--;
        gen_res(res,curr,row_st,row_end,line_st,line_end);
    }
};



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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值