Skip to content

Commit fe0ff9f

Browse files
authored
Add files via upload
1 parent 61f2a27 commit fe0ff9f

File tree

3 files changed

+69
-0
lines changed

3 files changed

+69
-0
lines changed
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
# 如果最终能整排值相同,那么两排各自的第一个多米诺骨牌至少有一个是目标值
2+
# 取两排第一个值分别进行判断,检查其他多米诺骨牌是否出现该值,若都出现则求出最小翻转次数
3+
class Solution(object):
4+
def minDominoRotations(self, A, B):
5+
def check(x, n):
6+
a, b = 0, 0
7+
for i in range(n):
8+
if A[i] != x and B[i] != x:
9+
return -1
10+
elif A[i] != x:
11+
a += 1
12+
elif B[i] != x:
13+
b += 1
14+
return min(a, b)
15+
16+
n = len(A)
17+
res = check(A[0], n)
18+
if res != -1:
19+
return res
20+
else:
21+
return check(B[0], n)
Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
class Solution(object):
2+
def shortestPathBinaryMatrix(self, grid):
3+
# 左上角和右下角不是0
4+
if grid[0][0] or grid[-1][-1]:
5+
return -1
6+
n, queue, d = len(grid), [(0, 0, 2)], [(-1, -1), (-1, 0), (-1, 1), (0, -1), (0, 1), (1, -1), (1, 0), (1, 1)]
7+
if n <= 2:
8+
return n
9+
# 从起点开始,广度优先搜索
10+
for x, y, res in queue:
11+
# 搜索八个方向
12+
for dx, dy in d:
13+
nx, ny = x+dx, y+dy
14+
if 0 <= nx < n and 0 <= ny < n and not grid[nx][ny]:
15+
# 有一条路径已经到达终点,返回路径长度
16+
if nx == n-1 and ny == n-1:
17+
return res
18+
# 未到达终点,添加中间位置到队列
19+
queue += [(nx, ny, res+1)]
20+
# 搜索过的位置置1,防止重复搜索
21+
grid[nx][ny] = 1
22+
# 没有路径到达终点
23+
return -1

leetcode2/1162.地图分析.py

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
# 广度优先搜索,从1开始,向四周搜索0,并记录每个0的搜索步数,返回最大的搜索步数
2+
class Solution(object):
3+
def maxDistance(self, grid):
4+
m, n = len(grid), len(grid[0])
5+
if sum([sum(grid[i]) for i in range(m)]) in [0, m * n]:
6+
return -1
7+
8+
q, res = [], [[-1] * n for _ in range(m)]
9+
d = [(1, 0), (-1, 0), (0, 1), (0, -1)]
10+
11+
for i in range(m):
12+
for j in range(n):
13+
if grid[i][j] == 1:
14+
res[i][j] = 0
15+
q.append((i, j))
16+
17+
while q:
18+
x, y = q.pop(0)
19+
for dx, dy in d:
20+
nx, ny = x + dx, y + dy
21+
if 0 <= nx < m and 0 <= ny < n and res[nx][ny] == -1:
22+
res[nx][ny] = res[x][y] + 1
23+
q.append((nx, ny))
24+
25+
return max([max(res[i]) for i in range(m)])

0 commit comments

Comments
 (0)