在我看来,语言真的不是太重要,程序员的个人财富在于思想,语言终归只是一种工具,今天发一下自己用sql写的8皇后,用到了递归回溯算法:
TryRow @N,@Row,@Result 是主函数
@N表示N皇后,@Row表示处理第几行 @Result保存皇后的摆放位置,每行用一个字符记录列的位置,例如
@Result="3142";表示第一行3列,第二行第1列,第三行第4列,第四行第2列
if Object_id('PrintResult') is not null
drop proc PrintResult
go
--打印结果
create proc PrintResult
@N int,@Result varchar(100)
as
declare
@Row int,@Col int
BEGIN
print '---------------------------------------'
set @Row=1
while @Row<=@N
BEGIN
set @Col=substring(@Result,@Row,1)
print Left(REPLICATE('0',@Col-1)+'X'+REPLICATE('0',100),@N)
set @Row=@Row+1
END
print '---------------------------------------'
END
go
-------------------------------------------
if Object_id('CheckValid') is not null
drop proc CheckValid
go
create proc CheckValid
@N int,@Row int,@Col int,@Result varchar(100),@bFlag bit out
as
declare @i int,@j int
begin
set @i=1
set @bFlag=0
while @i<@Row
begin
set @j=SubString(@Result,@i,1)
if (@j=@Col) or (abs(@j-@Col)=abs(@i-@Row))
return
set @i=@i+1
end
set @bFlag=1
end
go
---------------------------------------------
if object_id('TryRow') is not null
drop proc TryRow
go
create proc TryRow
@N int,@Row int,@Result varchar(100)
as
declare
@Col int,@bFlag bit,@tStr varchar(100),@tRow int
BEGIN
if @Row>@N
begin
--输出8皇后
exec PrintResult @N,@Result
return
END
set @Col=1
while @Col<=@N
begin
exec CheckValid @N,@Row,@Col,@Result,@bFlag out
if @bFlag=1
begin
set @tStr=@Result+Cast(@Col as varchar(1))
set @tRow=@Row+1
--判断 @Row,@Col位置是否有效
exec TryRow @N = @N, @Row = @tRow, @Result = @tStr
end
set @Col=@Col+1
end
END
go
set nocount on
exec TryRow @N = 8, @Row = 1, @Result = ''
执行后,程序输出结果如下:
---------------------------------------
X0000000
0000X000
0000000X
00000X00
00X00000
000000X0
0X000000
000X0000
---------------------------------------
---------------------------------------
X0000000
00000X00
0000000X
00X00000
000000X0
000X0000
0X000000
0000X000
---------------------------------------
---------------------------------------
X0000000
000000X0
000X0000
00000X00
0000000X
0X000000
0000X000
00X00000
---------------------------------------
---------------------------------------
X0000000
000000X0
0000X000
0000000X
0X000000
000X0000
00000X00
00X00000
---------------------------------------
---------------------------------------
0X000000
000X0000
00000X00
0000000X
00X00000
X0000000
000000X0
0000X000
---------------------------------------
后面的结果略