o1-mini-2024-09-12· OpenAI
WildChat-4.8M (AI2)
用fortran解八皇后
- User
用fortran解八皇后
- Assistant
用fortran解八皇后
以下是使用 Fortran 实现的八皇后问题的解法。该程序采用回溯算法查找所有可能的解决方案,并将每个解的棋盘布局输出到屏幕上。
数据结构:
queen(8) 来表示每一行皇后的位置。queen(i) 表示第 i 行皇后所在的列。算法步骤:
输出:
program EightQueens
implicit none
integer, parameter :: N = 8
integer :: queen(N)
integer :: row, solutions
solutions = 0
call solve(1, queen, solutions)
print *, "Total solutions found: ", solutions
contains
recursive subroutine solve(row, queen, solutions)
integer, intent(in) :: row
integer, intent(inout) :: queen(N)
integer, intent(inout) :: solutions
integer :: col, prevRow
if (row > N) then
solutions = solutions + 1
call printSolution(queen)
return
end if
do col = 1, N
if (isSafe(row, col, queen)) then
queen(row) = col
call solve(row + 1, queen, solutions)
end if
end do
end subroutine solve
logical function isSafe(row, col, queen)
integer, intent(in) :: row, col
integer, intent(in) :: queen(N)
integer :: i
isSafe = .true.
do i = 1, row - 1
if (queen(i) == col .or. &
abs(queen(i) - col) == abs(i - row)) then
isSafe = .false.
return
end if
end do
end function isSafe
subroutine printSolution(queen)
integer, intent(in) :: queen(N)
integer :: i, j
print *, "Solution ", :
do i = 1, N
write(*, '(8I2)') queen
exit
end do
do i = 1, N
do j = 1, N
if (queen(i) == j) then
write(*, '(A)', advance='no') "Q "
else
write(*, '(A)', advance='no') ". "
end if
end do
print *
end do
print *
end subroutine printSolution
end program EightQueens
主程序 EightQueens:
queen 和解的计数器 solutions。solve 从第1行开始尝试放置皇后。递归子程序 solve:
row 表示当前要放置皇后的行数。row > N,说明所有8个皇后都已成功放置,调用 printSolution 输出当前解,并将解计数器 solutions 加1。col 放置皇后,检查是否安全(调用 isSafe 函数)。queen(row),并递归调用 solve 处理下一行。函数 isSafe:
row 行 col 列放置皇后是否与之前放置的皇后冲突。queen(i) == col)。abs(queen(i) - col) == abs(i - row))。isSafe 表示当前位置是否安全。子程序 printSolution:
queen。Q 表示皇后,. 表示空位。运行该程序后,你将看到类似如下的输出(这里只展示部分解):
Solution
Q . . . . . . .
. . . Q . . . .
. . . . . . Q .
. . . . . . . Q
. Q . . . . . .
. . . . Q . . .
. . Q . . . . .
. . . . . Q . .
...
Total solutions found: 92
确保你有 Fortran 编译器(如 gfortran)安装在你的系统上。保存上述代码到一个文件,例如 eight_queens.f90,然后使用以下命令进行编译和运行:
gfortran -o eight_queens eight_queens.f90
./eight_queens
这将编译程序并执行,输出所有92个解及其总数。
Not yet included in a published release.