59. Spiral Matrix II
2017-01-01 16:01
337 查看
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 ]
]
For example,
Given n = 3,
You should return the following matrix:
[
[ 1, 2, 3 ],
[ 8, 9, 4 ],
[ 7, 6, 5 ]
]
public class Solution { public int[][] generateMatrix(int n) { int[][] res = new int ; int rowbegin = 0, rowend = n-1, colbegin = 0, colend = n-1; int index = 1; while(rowbegin <= rowend && colbegin <= colend){ for(int i = colbegin; i <= colend; i++){ res[rowbegin][i] = index++; } rowbegin++; for(int i = rowbegin; i <= rowend; i++){ res[i][colend] = index++; } colend--; if(rowbegin <= rowend){ for(int i = colend; i >= colbegin; i--){ res[rowend][i] = index++; } } rowend--; if(colbegin <= colend){ for(int i = rowend; i >= rowbegin; i--){ res[i][colbegin] = index++; } } colbegin++; } return res; } }
相关文章推荐
- leetcode 179 Largest Number
- leetcode 24 Swap Nodes in Pairs
- leetcode 2 Add Two Numbers 方法1
- leetcode 2 Add Two Numbers 方法2
- leetcode刷题,没想到这么难搞!
- leetcode----Longest Substring Without Repeating Characters
- [LeetCode]47 Permutations II
- [LeetCode]65 Valid Number
- [LeetCode]123 Best Time to Buy and Sell Stock III
- [LeetCode] String Reorder Distance Apart
- [LeetCode] Sliding Window Maximum
- [LeetCode] Find the k-th Smallest Element in the Union of Two Sorted Arrays
- [LeetCode] Determine If Two Rectangles Overlap
- [LeetCode] A Distance Maximizing Problem
- leetcode_linearList
- leetcode_linearList02
- 021-Merge Two Sorted Lists(合并两个排好序的单链表);leetcode
- LeetCode[Day 1] Two Sum 题解
- LeetCode[Day 2] Median of Two Sorted Arrays 题解
- LeetCode[Day 3] Longest Substring Without... 题解