Given a positive integer n, generate a square matrix filled with elements from 1 to n^2 in spiral order.
給一個正整數n,請產生一個方陣,照螺旋的順序填入1到n^2。
Example:
Input: 3
Output:
[
[ 1, 2, 3 ],
[ 8, 9, 4 ],
[ 7, 6, 5 ]
]
i
去紀錄現在產生到哪裡。x
和y
去紀錄現在的位置。dir
去控制下一次的位置。
class Solution {
public:
vector<vector<int>> generateMatrix(int n) {
vector<vector<int>> ans(n,vector<int>(n,0));
int x=0,y=0;
int dir=0;
for(int i=1;;i++)
{
//set
ans[y][x]=i;
if(i==n*n)
break;
//control dir
while(1)
{
if(dir%4==0)
{
if(x!=n-1 && ans[y][x+1]==0)
break;
}
else if(dir%4==1)
{
if(y!=n-1 && ans[y+1][x]==0)
break;
}
else if(dir%4==2)
{
if(x!=0 && ans[y][x-1]==0)
break;
}
else
{
if(y!=0 && ans[y-1][x]==0)
break;
}
dir++;
}
//move
if(dir%4==0)
{
x++;
}
else if(dir%4==1)
{
y++;
}
else if(dir%4==2)
{
x--;
}
else
{
y--;
}
}
return ans;
}
};
LeetCode
C++
1. Two Sum
Nov 15, 2023You are given an array of positive integers arr. Perform some operations (possibly none) on arr so that it satisfies these conditions:
Nov 15, 2023Given a string s, return the number of homogenous substrings of s. Since the answer may be too large, return it modulo 109 + 7.
Nov 9, 2023There are n computers numbered from 0 to n - 1 connected by ethernet cables connections forming a network where connections[i] = [ai, bi] represents a connection between computers ai and bi. Any computer can reach any other computer directly or indirectly through the network.
Nov 9, 2023or
By clicking below, you agree to our terms of service.
New to HackMD? Sign up