Day-8 Leetcode Coding Journey: Mastering Problem-Solving Techniques
LeetCode #59: Spiral Matrix II
Problem Statement
Given a positive integer n
, generate an n x n
matrix filled with elements from 1
to n^2
in spiral order.
Constraints
- 1≤n≤20
🚀 Code Implementation
class Solution(object):
def generateMatrix(self, n):
"""
:type n: int
:rtype: List[List[int]]
"""
matrix=[]
for i in range(n):
row=[0]*n
matrix.append(row)
left,right,top,bottom=0,n-1,0,n-1
num=1
while left<=right and top<=bottom:
for i in range(left,right+1):
matrix[top][i]=num
num+=1
top+=1
for i in range(top,bottom+1):
matrix[i][right]=num
num+=1
right-=1
if top<=bottom:
for i in range(right,left-1,-1):
matrix[bottom][i]=num
num+=1
bottom-=1
if left<=right:
for i in range(bottom,top-1,-1):
matrix[i][left]=num
num+=1
left+=1
return matrix
LeetCode #62: Unique Paths
Problem Statement
A robot is located at the top-left corner of an m x n
grid.
The robot can only move right or down at any point in time.
The robot must reach the bottom-right corner of the grid.
Find the number of unique paths the robot can take to reach its destination.
Constraints
- 1≤m,n≤100
🚀 Code Implementation
class Solution(object):
def uniquePaths(self, m, n):
"""
:type m: int
:type n: int
:rtype: int
"""
dp=[]
for i in range(m):
row=[1]*n
dp.append(row)
for i in range(1,m):
for j in range(1,n):
dp[i][j]=dp[i-1][j]+dp[i][j-1]
return dp[m-1][n-1]