Created
March 5, 2020 05:22
-
-
Save phongngtuan/8f97a43ea926e4aa4e562f2a317d87ee to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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