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 ]
]
和上一道题leetcode 54. Spiral Matrix 螺旋方式读取矩阵相反的是,本题要求的是按照螺旋的方式写矩阵,实现方法一模一样。
代码如下:
public class Solution
{
public int[][] generateMatrix(int n)
{
if(n==0)
return new int[0][0];
int [][]matrix=new int[n][n];
int count=1;
int top=0,bottom=matrix.length-1;
int left=0,right=matrix[0].length-1;
while(true)
{
for(int i=left;i<=right;i++)
matrix[top][i]=count++;
top++;
if(top>bottom)
break;
for(int i=top;i<=bottom;i++)
matrix[i][right]=count++;
right--;
if(left>right)
break;
for(int i=right;i>=left;i--)
matrix[bottom][i]=count++;
bottom--;
if(top>bottom)
break;
for(int i=bottom;i>=top;i--)
matrix[i][left]=count++;
left++;
if(left>right)
break;
}
return matrix;
}
}
下面是C++的做法,这个和上一道题螺旋方式读取矩阵的做法一模一样
代码如下:
#include <iostream>
#include <vector>
#include <map>
#include <unordered_map>
#include <set>
#include <unordered_set>
#include <queue>
#include <stack>
#include <string>
#include <climits>
#include <algorithm>
#include <sstream>
#include <functional>
#include <bitset>
#include <numeric>
#include <cmath>
#include <regex>
using namespace std;
class Solution
{
public:
vector<vector<int>> generateMatrix(int n)
{
vector<vector<int>> mat(n,vector<int>(n,0));
if (n <= 0)
return mat;
int count = 1 , left = 0, right = mat[0].size() - 1;
int up = 0, down = mat.size() - 1;
while (true)
{
for (int i = left; i <= right; i++)
mat[up][i] = count++;
up++;
if (up > down)
break;
for (int i = up; i <= down; i++)
mat[i][right] = count++;
right--;
if (left > right)
break;
for (int i = right; i >= left; i--)
mat[down][i] = count++;
down--;
if (up > down)
break;
for (int i = down; i >= up; i--)
mat[i][left] = count++;
left++;
if (left > right)
break;
}
return mat;
}
};