leetcode #59 in cpp

本文介绍了一个生成螺旋矩阵的算法,该算法能够根据给定的整数n生成一个n×n的螺旋矩阵,矩阵元素从1到n²按螺旋顺序填充。通过详细解析代码流程,展示了如何实现这一过程。

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

Solution:

I directly list 4 cases about how we proceed. The code is quite long but straightforward and clear.  

Code:

class Solution {
public:
    vector<vector<int>> generateMatrix(int n) {
        vector<vector<int>> res(n,vector<int>(n,0));
        int cur_row = 0;
        int cur_col = 0;
        int upper_row = n-1;
        int lower_row = 0;
        int upper_col = n-1;
        int lower_col = 0;
        int count = 1;
        while(count<=n*n){
            res[cur_row][cur_col] = count;
            if(cur_row == lower_row){//at the upper row
                if(cur_col == upper_col){//should turn down
                    cur_row ++;
                }else{//should go right
                    cur_col ++;
                }
            }else if(cur_col == upper_col){//at the right col
                if(cur_row == upper_row){//should turn left
                    cur_col --;
                }else{//should go down
                    cur_row ++;
                }
            }else if(cur_row == upper_row && upper_row != lower_row){//at the bottom
                if(cur_col != lower_col){//should go left 
                    cur_col --;
                }else{//should turn up
                    cur_row --;
                }
                
            }else if(upper_col != lower_col){//cur_col == lower_col, at the left side
                
                    if(cur_row != lower_row + 1){//can go up
                        cur_row --;
                    }else{//go right to the next submatrix
                        cur_col ++;
                        upper_row --;
                        lower_row ++;
                        upper_col --;
                        lower_col ++;
                    }
            }
            
            count++;
        }
        return res;
    }
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值