尝试在C中制作一个程序来解决具有M皇后问题的N尺寸三角形板。甚至无法让它发挥作用。我猜它崩溃了,因为我错误地使用了数组。能告诉我这里我做错了什么吗?
#include <stdlib.h>
#include <stdio.h>
int checkPlaceability(int n, int (*board)[n], int row, int col);
int placeQueens(int n, int m, int (*board)[n], int col);
void main()
{
int n;
int board[n][n];
int m;
printf("Enter board size: \n");
scanf("%d", &n);
printf("Enter queen count: \n");
scanf("%d", &m);
if(placeQueens(n, m, board, 0) == 0)
{
printf("Solution doesn't exist");
}
else
{
printf("Solution exists");
}
}
checkPlaceability(int n, int (*board)[n], int row, int col)
{
int i;
int j;
for(i = col; i < i++)
{
if(board[i][col] == 1)
{
return 0;
}
}
for(i = 0; i < n; i++)
{
if(board[row][i] == 1)
{
return 0;
}
}
for(i = abs(row - col)+1, j = 0; i < j && j < n; i++, j++)
{
if(board[i][j] == 1)
{
return 0;
}
}
return 1;
}
int placeQueens(int n, int m, int (*board)[n], int col)
{
int i;
int queenCount = m;
if(col >= n)
{
return 1;
}
for(i = 0; i < m; i++)
{
if(checkPlaceability(n, board, i, col) == 1)
{
board[i][col] = 1;
queenCount--;
if(queenCount == 0)
{
return 1;
}
if(placeQueens(n, queenCount, board, col+1) == 1)
{
return 1;
}
board[i][col] = 0;
}
}
return 0;
}
答案 0 :(得分:3)
你宣布:
int board[n][n];
在初始化n ...之前...
解决方案:
举:
int board[n][n];
到输入语句之后。