Leetcode4 Spiral Matrix II
来源:互联网 发布:电脑软件打开乱码 编辑:程序博客网 时间:2024/05/17 06:06
1、题目描述
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 ]
]
2、解题思路
将矩阵赋值分为四部分,向右、向下、向左、向上四个方向上的循环赋值
3、代码
#include<iostream>using namespace std;int main(){ int n; cout<<"please input the n: "; cin>>n; int matrix[n][n]; int i=0,j=0,x=n,y=n,left=n*n,temp=1; while(left--){ //toword rigt for(int k=i;k<x;++k){ matrix[j][k]=temp; ++temp; } ++j; //toward down for(int k=j;k<y;++k){ matrix[k][x-1]=temp; ++temp; } --x; //toward left for(int k=x-1;k>=i;--k){ matrix[y-1][k]=temp; ++temp; } --y; //toward up for(int k=y-1;k>=j;--k){ matrix[k][i]=temp; ++temp; } ++i; } //output for(int k1=0;k1<n;++k1){ for(int k2=0;k2<n;++k2){ cout<<matrix[k1][k2]<<"\t"; } cout<<endl; } return 0;}
4、结果图
0 0
- Leetcode4 Spiral Matrix II
- Spiral Matrix && 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
- LeetCode-Spiral Matrix II
- [leetcode] Spiral Matrix II
- LeetCode - Spiral Matrix II
- Project Euler Problem 8: Largest product in a series
- Javacc词法分析初练
- 生成1~n的全排列
- php操作redis
- Android 图片库universal-image-loader(二)
- Leetcode4 Spiral Matrix II
- 图像处理---傅里叶变化基础
- MyBatis自动生成实体、DAO接口、Mapping映射文件
- Binary Tree Paths
- C语言基础笔记
- 【九度OJ】题目1195:最长&最短文本 解题报告
- LinkedHashMap和HashMap
- L1-007. 念数字
- 搭建SpringBoot-MyBatis-MyBatisGenerator项目