-
Notifications
You must be signed in to change notification settings - Fork 30
/
SpiralMatrixII.cs
executable file
·76 lines (72 loc) · 3.79 KB
/
SpiralMatrixII.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
// Source : https://leetcode.com/problems/spiral-matrix-ii/
// Author : codeyu
// Date : Saturday, December 10, 2016 10:33:16 PM
/**********************************************************************************
*
* 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 ]
* ]
*
*
**********************************************************************************/
using System;
using System.Collections.Generic;
using Algorithms.Utils;
namespace Algorithms
{
public class Solution059
{
public static int[,] GenerateMatrix(int n)
{
if(n<0) return null;
var result = new int[n,n];
var top = 0;
var bottom = n-1;
var left = 0;
var right = n-1;
var num = 1;
while(top <= bottom)
{
if(top == bottom)
{
result[top, top] = num++;
}
//first line
for(int i=left;i<right;i++)
{
result[top, i] = num++;
}
//right line
for(int i=top;i<bottom;i++)
{
result[i, right] = num++;
}
//bootom line
for(int i=right;i>left;i--)
{
result[bottom, i] = num++;
}
//left line
for(int i=bottom;i>top;i--)
{
result[i,left] = num++;
}
top++;
bottom--;
left++;
right--;
}
return result;
}
}
}