
本文将详细介绍如何使用 Z3 定理证明器在 Python 中解决冰冻湖寻路问题。我们将详细讲解如何将问题转化为 Z3 可以理解的约束条件,并提供完整的代码示例,帮助读者理解如何使用 Z3 找到从起点到终点的安全路径。本文重点在于如何正确建模问题,以及如何使用 Z3 的 API 来表达约束和求解。
给定一个由 1(安全)和 0(不安全)组成的矩阵,代表一个冰冻湖。目标是找到一条从起始位置到目标位置的安全路径,即路径上的所有单元格都必须是安全的(值为 1)。 只能在相邻的单元格之间移动(上、下、左、右)。
解决此问题的关键在于正确地将问题建模为 Z3 可以理解的约束。我们不应该为矩阵中的每个单元格创建符号变量,而是应该为路径本身创建变量。这允许我们直接约束路径的有效性。
首先,我们需要定义表示路径的变量。 由于我们不知道路径的长度,我们可以假设最坏的情况是路径包含矩阵中的所有单元格。 因此,我们可以为路径中的每个可能的位置创建整数变量,表示其行和列坐标。
from z3 import *
def find_path(matrix, start, end):
# Define the dimensions of the matrix
rows = len(matrix)
cols = len(matrix[0])
# symbolic look-up into the matrix:
def lookup(x, y):
val = 0
for r in range(rows):
for c in range(cols):
val = If(And(x == r, y == c), matrix[r][c], val)
return val
# Create a path, there are at most rows*cols elements
path = []
for r in range(rows):
for c in range(cols):
path.append([FreshInt(), FreshInt()])在这里,path 是一个列表,其中每个元素都是包含两个 FreshInt() 变量的列表,分别代表行和列的索引。 FreshInt() 创建一个新的整数变量,其名称与之前创建的任何变量不同。 lookup 函数用于查找矩阵中给定坐标的值。
接下来,我们需要添加约束来确保路径有效。 这包括以下内容:
s = Solver()
# assert that the very first element of the path is the start position:
s.add(path[0][0] == start[0])
s.add(path[0][1] == start[1])
# for each remaining path-element, make sure either we reached the end, or it's a valid move
prev = path[0]
done = False
for p in path[1:]:
valid1 = And(p[0] >= 0, p[0] < rows, p[1] >= 0, p[1] < cols) # Valid coords
valid2 = Or( And(p[0] == prev[0]-1, p[1] == prev[1]) # Go up
, And(p[0] == prev[0]+1, p[1] == prev[1]) # or Go down
, And(p[0] == prev[0], p[1] == prev[1]+1) # or Go right
, And(p[0] == prev[0], p[1] == prev[1]-1)) # or Go left
valid3 = lookup(p[0], p[1]) == 1 # The cell is safe
# Either we're done, or all valid conditions must hold
s.add(Or(done, And(valid1, valid2, valid3)))
prev = p
# We're done if p is the end position:
done = Or(done, And(p[0] == end[0], p[1] == end[1]))
# Make sure the path is unique:
for i in range(len(path)):
for j in range(len(path)):
if j <= i:
continue
s.add(Or(path[i][0] != path[j][0], path[i][1] != path[j][1]))代码解释:
最后,我们使用 Z3 求解器来查找满足所有约束的路径。 如果找到这样的路径,我们将从模型中提取它。
# Compute the path:
if s.check() == sat:
model = s.model()
walk = []
for p in path:
cur = [model[p[0]].as_long(), model[p[1]].as_long()]
walk.append(cur)
if (cur[0] == end[0] and cur[1] == end[1]):
break
return walk
else:
return None代码解释:
from z3 import *
def find_path(matrix, start, end):
# Define the dimensions of the matrix
rows = len(matrix)
cols = len(matrix[0])
# symbolic look-up into the matrix:
def lookup(x, y):
val = 0
for r in range(rows):
for c in range(cols):
val = If(And(x == r, y == c), matrix[r][c], val)
return val
# Create a path, there are at most rows*cols elements
path = []
for r in range(rows):
for c in range(cols):
path.append([FreshInt(), FreshInt()])
s = Solver()
# assert that the very first element of the path is the start position:
s.add(path[0][0] == start[0])
s.add(path[0][1] == start[1])
# for each remaining path-element, make sure either we reached the end, or it's a valid move
prev = path[0]
done = False
for p in path[1:]:
valid1 = And(p[0] >= 0, p[0] < rows, p[1] >= 0, p[1] < cols) # Valid coords
valid2 = Or( And(p[0] == prev[0]-1, p[1] == prev[1]) # Go up
, And(p[0] == prev[0]+1, p[1] == prev[1]) # or Go down
, And(p[0] == prev[0], p[1] == prev[1]+1) # or Go right
, And(p[0] == prev[0], p[1] == prev[1]-1)) # or Go left
valid3 = lookup(p[0], p[1]) == 1 # The cell is safe
# Either we're done, or all valid conditions must hold
s.add(Or(done, And(valid1, valid2, valid3)))
prev = p
# We're done if p is the end position:
done = Or(done, And(p[0] == end[0], p[1] == end[1]))
# Make sure the path is unique:
for i in range(len(path)):
for j in range(len(path)):
if j <= i:
continue
s.add(Or(path[i][0] != path[j][0], path[i][1] != path[j][1]))
# Compute the path:
if s.check() == sat:
model = s.model()
walk = []
for p in path:
cur = [model[p[0]].as_long(), model[p[1]].as_long()]
walk.append(cur)
if (cur[0] == end[0] and cur[1] == end[1]):
break
return walk
else:
return None
# Example usage
matrix = [[1, 1, 1, 0],
[1, 0, 1, 0],
[1, 0, 1, 0],
[1, 0, 0, 0]]
start = (3, 0)
end = (2, 2)
path = find_path(matrix, start, end)
if path:
print("Valid path found:")
for cell in path:
print(f"({chr(ord('A') + cell[0])}{cell[1] + 1})")
else:
print("No valid path found.")通过使用 Z3 定理证明器,我们可以有效地找到冰冻湖上的安全路径。 这种方法可以推广到其他寻路问题,只需根据特定问题的要求调整约束即可。
以上就是使用 Z3 求解器寻找冰冻湖上的路径的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号