Skip to content

Instantly share code, notes, and snippets.

@phongngtuan
Created March 5, 2020 05:22
Show Gist options
  • Select an option

  • Save phongngtuan/8f97a43ea926e4aa4e562f2a317d87ee to your computer and use it in GitHub Desktop.

Select an option

Save phongngtuan/8f97a43ea926e4aa4e562f2a317d87ee to your computer and use it in GitHub Desktop.
class Solution:
def generateMatrix(self, n: int) -> List[List[int]]:
if n == 1:
return [[1]]
mat = [[0 for i in range(n)] for j in range(n)]
counter = 1
for i in range(0, n):
x, y = i, i
width = n - i * 2
height = width - 2
#right
for _ in range(width):
mat[y][x] = counter
x += 1
counter += 1
#down
x -= 1
y += 1
if mat[y][x]: return mat
for _ in range(height):
mat[y][x] = counter
y += 1
counter += 1
#left
if mat[y][x]: return mat
for _ in range(width):
mat[y][x] = counter
x -= 1
counter += 1
#up
x += 1
y -= 1
if mat[y][x]: return mat
for _ in range(height):
mat[y][x] = counter
y -= 1
counter += 1
return ma
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment