Spiral Matrix II问题及解法
来源:互联网 发布:让人惊艳的古诗词知乎 编辑:程序博客网 时间:2024/06/11 18:33
问题描述:
Given an integer n, generate a square matrix filled with elements from 1 to n2 in spiral order.
示例:
Given n = 3
,
[ [ 1, 2, 3 ], [ 8, 9, 4 ], [ 7, 6, 5 ]]问题分析:
该题目与Spiral Matrix题目原理一致,这里不多赘述。
过程详见代码:
class Solution {public: vector<vector<int>> generateMatrix(int n) { if (n == 0) return vector<vector<int>>{};int num = n * n;int dict = 0; // right - 0; down - 1; left - 2; up - 3int row = 0, col = 0;vector<vector<int>> used(n, vector<int>(n, 0));for (int i = 1; i <= num;){switch (dict){case 0:if (col < n){if (!used[row][col]){used[row][col] = i;col++;i++;}else{dict = (dict + 1) % 4;row++;col--;}}else{col--;dict = (dict + 1) % 4;row++;}break;case 1:if (row < n){if (!used[row][col]){used[row][col] = i;row++;i++;}else{dict = (dict + 1) % 4;col--;row--;}}else{row--;dict = (dict + 1) % 4;col--;}break;case 2:if (col >= 0){if (!used[row][col]){used[row][col] = i;col--;i++;}else{dict = (dict + 1) % 4;col++;row--;}}else{col++;row--;dict = (dict + 1) % 4;}break;case 3:if (row >= 0){if (!used[row][col]){used[row][col] = i;row--;i++;}else{dict = (dict + 1) % 4;row++;col++;}}else{dict = (dict + 1) % 4;row++;col++;}break;}}return used; }};
阅读全文
0 0
- Spiral Matrix II问题及解法
- Spiral Matrix问题及解法
- Spiral Matrix && Spiral Matrix II
- Search a 2D Matrix II问题及解法
- Leetcode之Spiral Matrix II 问题
- LeetCode: Spiral Matrix II
- LeetCode Spiral Matrix II
- [Leetcode] Spiral Matrix II
- LeetCode : Spiral Matrix II
- Spiral Matrix II
- [LeetCode] Spiral Matrix II
- Spiral Matrix II
- Spiral Matrix II
- [LeetCode]Spiral Matrix II
- Spiral Matrix II
- Spiral Matrix I(II)
- Spiral Matrix II
- [leetcode]Spiral Matrix II
- JSP&Servlet servlet生成报表
- 求数组的小和
- Promise深入理解
- python杂记
- JS实现点击按钮,复制文本框中的的内容
- Spiral Matrix II问题及解法
- access批量快速插入(DAO方法)
- LeetCode 167. Two Sum II
- 包装盒设计软件(3D Real Boxshot) v5.0 汉化免费版
- mac mysql没法启动 Waring:The /usr/local/mysql/data directory is not owned by the mysql/_mysql
- 最新 macOS Sierra 10.12.6 安装CocoaPods及使用详
- SpringMVC实现文件的上传与下载
- Kylin实例Cube实验
- scanner的详细解答用法