当前位置:网站首页>[leetcode]Spiral Matrix II

[leetcode]Spiral Matrix II

2022-07-07 04:06:00 Full stack programmer webmaster

Hello everyone , I meet you again , I'm the king of the whole stack

A narrative statement of the problem :

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

The basic idea :

This topic is the last one 《Spiral Matrix》 Deformation of . It can be assigned with the same traversal method . Create a rotation matrix .

Code :

vector<vector<int> > generateMatrix(int n) { //C++
        vector<vector<int> >result;
        if(n <=0 )
            return result;
        
        for(int i = 0; i < n; i++){
            vector<int> tmp(n,0);
            result.push_back(tmp);
        }
        
        int rowBegin = 0;
        int rowEnd   = n-1;
        int colBegin = 0;
        int colEnd   = n-1;
        
        int count = 1;
        while(rowBegin <= rowEnd && colBegin <= colEnd){
            //to right
            for(int j = colBegin; j <= colEnd; j++)
                result[rowBegin][j] =count++;
            rowBegin++;
            
            //to down
            for(int j = rowBegin; j <= rowEnd; j++)
                result[j][colEnd] = count++;
            colEnd--;
            
            //to left
            if(rowBegin <= rowEnd){
                for(int j = colEnd; j >= colBegin; j--)
                    result[rowEnd][j] = count++;
            }
            rowEnd--;
            
            //to up
            if(colBegin <= colEnd){
                for(int j = rowEnd; j >= rowBegin; j--)
                    result[j][colBegin] = count++;
            }
            colBegin++;
        }
        return result;
    }

Publisher : Full stack programmer stack length , Reprint please indicate the source :https://javaforall.cn/116707.html Link to the original text :https://javaforall.cn

原网站

版权声明
本文为[Full stack programmer webmaster]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/188/202207062125243786.html