|
发表于 2011-7-20 22:59:58
|
显示全部楼层
本帖最后由 紫色枫叶 于 2011-7-20 23:09 编辑
chao_prince 发表于 2011-7-12 13:28
最近有点事,都没过来,今天继续、、
恩,这个算法是经典算法,记得以前学java的时候看过。差不多都还给老师了。经你这么一写,醍醐灌顶。我在你的代码基础上稍微做了些修改。
- #include <stdio.h>
- #include <stdlib.h>
- #define TRUE 1
- #define FALSE 0
- int **board;
- void print_board(int n)
- {
- int row;
- int column;
- static int n_soluctions;
- n_soluctions += 1;
- printf( "Soluctions #%d:\n", n_soluctions );
- for( row = 0; row < n; row += 1 )
- {
- for( column = 0; column < n; column += 1 )
- {
- if( board[row][column] )
- printf( " Q" );
- else
- printf( " +" );
- }
- putchar( '\n' );
- }
- putchar( '\n' );
- }
- int conflicts(int row, int column, int n)
- {
- int i;
- for( i = 1; i < n; i++ )
- {
- if(row - i >= 0 && board[row-i][column])
- return TRUE;
- if(column - i >= 0 && board[row][column-i])
- return TRUE;
- if(column + i < n && board[row][column+i])
- return TRUE;
- if(row - i >= 0 && column - i >= 0
- && board[row-i][column-i])
- return TRUE;
- if(row - i >= 0 && column + i < n
- && board[row-i][column+i])
- return TRUE;
- }
- return FALSE;
- }
- void place_queen(int row, int n)
- {
- int column;
- for(column = 0; column < n; column += 1)
- {
- board[row][column] = TRUE;
- if(row == 0 || !conflicts(row, column, n))
- {
- if(row < n - 1)
- place_queen(row+1, n);
- else
- print_board(n);
- }
- board[row][column] = FALSE;
- }
- }
- int main(int argc, char **argv)
- {
- printf("请输入皇后数(偶数):");
- int n = 0;
- scanf("%d", &n);
- board = new int*[n];
- for(int i = 0; i < n; i++)
- {
- board[i] = new int[n];
- }
-
- for(int i = 0; i < n; i++)
- {
- for(int j = 0; j < n; j++)
- board[i][j] = FALSE;
- }
- place_queen(0, n);
- for(int i = 0; i < n; i++)
- {
- delete [] board[i];
- board[i] = NULL;
- }
- delete []board;
- board = NULL;
- system("pause");
- return 0;
- }
复制代码
|
|