23.03.22 Today’s Leetcode
2492. Minimum Score of a Path Between Two Cities (medium)
class Solution:
def minScore(self, n: int, roads: List[List[int]]) -> int:
graph = defaultdict(dict)
for u, v, w in roads:
graph[u][v] = graph[v][u] = w
min_score = float('inf')
visited = set()
queue = deque([1])
while queue:
node = queue.popleft()
for adj, score in graph[node].items():
if adj not in visited:
queue.append(adj)
visited.add(adj)
min_score = min(min_score, score)
return min_score
1556. Thousand Separator (easy)
class Solution:
def thousandSeparator(self, n: int) -> str:
if n == 0:
return '0'
res = ''
count = 0
while n:
if count > 0 and count % 3 == 0:
res += '.'
res += str(n % 10)
count += 1
n = n // 10
return res[::-1]
1034. Coloring A Border (medium)
class Solution:
def colorBorder(self, grid: List[List[int]], row: int, col: int, color: int) -> List[List[int]]:
m, n = len(grid), len(grid[0])
def out_of_boundary(x, y):
return x < 0 or y < 0 or x >= m or y >= n
def get_color(x, y):
if out_of_boundary(x, y):
return -2
return grid[x][y]
def check_inside(x, y, target):
dirs = [1, 0, -1, 0]
for i in range(4):
color = get_color(x + dirs[i], y + dirs[(i + 1) % 4])
if color != -1 and color != target:
return False
return True
p = []
def dfs(x, y, target):
if out_of_boundary(x, y):
return
if grid[x][y] != target:
return
if check_inside(x, y, target):
p.append((x, y, grid[x][y]))
grid[x][y] = -1
dfs(x + 1, y, target)
dfs(x - 1, y, target)
dfs(x, y + 1, target)
dfs(x, y - 1, target)
dfs(row, col, grid[row][col])
for i in range(m):
for j in range(n):
if grid[i][j] == -1:
grid[i][j] = color
for x, y, color in p:
grid[x][y] = color
return grid