我正在尝试编写一个简短的 Julia 程序来解决 n 个皇后问题 - 您尝试将 n 个皇后放在 nxn 个棋盘上,这样它们就不会互相攻击 - 我是 Julia 的新手,我不明白当使用所需变量类型的参数类型定义 check 时,为什么会出现错误“MethodError:没有方法匹配 check(::Int64, ::Int64, ::Int64, ::BitMatrix)”。
我尝试在函数内和传递值之前详细说明变量类型,但它仍然尝试找到具有不同数据类型的方法。
下面列出了代码
solve(1, 6, falses(6, 6))
display(board)
function check(row::Int16, column::Int16, n::Int16, board::BitMatrix)
left::Int16 = 0
checkLeft::Bool = true
right::Int16 = 0
checkRight::Bool = true
for j::Int16 = row:-1:1
if left==column-1
checkLeft = false
else
left+=1
end
if right==n-column
checkRight = false
else
right+=1
end
if board[j,column]||(board[j,column-left]&&checkLeft)||(board[j,column+right]&&checkRight)
return true
end
end
return false
end
function solve(row::Int16, n::Int16, board::BitMatrix)
column::Int16 = 1
if row>=n
return true
end
for column = 1:n
if check(row, column, n, board)
board[row,column] = true
if solve(row+1, n, board)
return true
end
board[row,column] = false
else
column+=1
end
end
return false
end
你的意思是你得到了
MethodError: no method matching solve(::Int64, ::Int64, ::BitMatrix)
。 solve
是错误的,而不是 check
。要最快修复,只需将所有 Int16
替换为 Int
:
function check(row::Int, column::Int, n::Int, board::BitMatrix)
left::Int = 0
checkLeft::Bool = true
right::Int = 0
checkRight::Bool = true
for j::Int = row:-1:1
if left==column-1
checkLeft = false
else
left+=1
end
if right==n-column
checkRight = false
else
right+=1
end
if board[j,column]||(board[j,column-left]&&checkLeft)||(board[j,column+right]&&checkRight)
return true
end
end
return false
end
function solve(row::Int, n::Int, board::BitMatrix)
column::Int = 1
if row>=n
return true
end
for column = 1:n
if check(row, column, n, board)
board[row,column] = true
if solve(row+1, n, board)
return true
end
board[row,column] = false
else
column+=1
end
end
return false
end
solve(1, 6, falses(6, 6))
此代码运行。问题是,在您的函数调用
solve(1, 6, falses(6, 6))
中,这些是 Int
,我猜在您的系统中默认为 Int64
(docs)。
一般来说,通常不需要显式指定函数参数的类型。这是一种常见的 Julia 反模式,已被多次记录和讨论。例如,请阅读此讨论主题。