Fortran 95 Source Code
! eight-queens
! Author: Hannes du Plooy
! Date: 20 Sep 2016
! Objective: To solve the following
! Search for a chess board solution with 8 queens and no one
! endangering any other.
! f95 -ffree-form eight-queens.for
program EightQueensProg
implicit none
integer ,dimension(8) :: board
integer :: i,j
if (EightQueens(0)) then
do i=0,7
do j=0,7
if (board(i) == j) then
print '(a,$)','Q'
else
print '(a,$)','.'
end if
end do
print *,''
end do
else
print *,'No Solution'
end if
contains
recursive function EightQueens(line) result(ans)
integer :: line
logical :: ans
integer :: column, line2
logical :: endangered
ans = .false.
if (line> 7) then
ans = .true.
else
do column=0,7
endangered = .false.
do line2=0,line-1
if ((board(line2) == column) .or. (abs(line-line2) == abs(column-board(line2)))) then
endangered = .true.
exit
end if
end do
if (.not. endangered) then
board(line) = column
if (EightQueens(line+1)) then
ans = .true.
exit
end if
end if
end do
end if
end function EightQueens
end program EightQueensProg