【经过几次优化后变为以下代码,采用回溯法】
#include <stdio.h>
#include <stdlib.h>
#define N 6
#define NOPRINTING //标志是否打印数组
//如果只是计算可能的情况的话,根本不需要N×N的棋盘数组。
void printMatrix(int* matrix, int m, int n){
int i,j
for(i=0i<mi++){
for(j=0j<nj++){
printf("%d ",matrix[n*i+j])
}
printf("\n")
}
}
void recusion(int* chessBoard, int n, int iter, int* count, int* col){
int i,j
#ifndef NOPRINTING
int* currentRow = &chessBoard[n*(n-iter)]
#endif
if(iter == 0){
(*count)++
#ifndef NOPRINTING
printMatrix(chessBoard, n, n)
printf("===============================\n")
#endif
return
}
for(i=0i<n-1i++){//布置每行第一个棋子
for(j=i+1j<nj++){//布置每行第二个棋子
#ifndef NOPRINTING
currentRow[i]=currentRow[j]=1//重写当前行
#endif
if(col[i]+1 <=2 &&col[j]+1 <=2){//有效
col[i]++
col[j]++
recusion(chessBoard, n, iter-1, count, col)//若当前仍满足要求,对下一行进行递归。
col[i]--
col[j]--
}
#ifndef NOPRINTING
currentRow[i]=currentRow[j]=0//清空当前行
#endif
}
}
}
void putChess(int* chessBoard, int n, int* count){
int* col=(int*)calloc(1,sizeof(int)*n)//标记每一列放置的棋子数
recusion(chessBoard, n, n, count, col)
free(col)
}
void main(){
int count=0
int chessBoard[N][N]={0}
printf("==========START TO PUT CHESS!===========\n")
putChess((int*)chessBoard, N, &count)
printf("All %d possible deploy!\n", count)
}
输出:
【N为3且选择打印】
==========START TO PUT CHESS!===========
1 1 0
1 0 1
0 1 1
===============================
1 1 0
0 1 1
1 0 1
===============================
1 0 1
1 1 0
0 1 1
===============================
1 0 1
0 1 1
1 1 0
===============================
0 1 1
1 1 0
1 0 1
===============================
0 1 1
1 0 1
1 1 0
===============================
All 6 possible deploy!
Press any key to continue
【N为8的时候,有近两亿种情况,花了将近一分钟的时间算完。】
==========START TO PUT CHESS!===========
All 187530840 possible deploy!
Press any key to continue
clsdim a$(4,4)
dim b(4)
for i=1 to 4
for j=1 to 4
for k=1 to 4
for l=1 to 4
for n=1 to 4
b(n)=0
next n
for x=1 to 4
for y=1 to 4
a$(x,y)=" "
next y
next x
a$(1,i)="(您要的棋子符号)"
b(i)=b(i)+1
a$(2,j)="(您要的棋子符号)"
b(j)=b(j)+1
a$(3,k)="(您要的棋子符号)"
b(k)=b(k)+1
a$(4,i)="(您要的棋子符号)"
b(l)=b(l)+1
if b(1)=b(2)=b(3)=b(4) then
for x=1 to 4
for y=1 to 4
?using"###"a$(x,y)
next y
?
next x
end
end if
next l
next k
next j
next i
end
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)