今有 6 x 6 的棋盘格。其中某些格子已经预先放好了棋子。现在要再放上去一些,使得:每行每列都正好有3颗棋子。我们希望推算出所有可能的放法。下面的代码就实现了这个功能。
初始数组中,“1”表示放有棋子,“0”表示空白。
int N = ; bool CheckStoneNum(int x[][])
{
for(int k=; k<; k++)
{
int NumRow = ;
int NumCol = ;
for(int i=; i<; i++)
{
if(x[k][i]) NumRow++;
if(x[i][k]) NumCol++;
}
if(_____________________) return false; // 填空
}
return true;
} int GetRowStoneNum(int x[][], int r)
{
int sum = ;
for(int i=; i<; i++) if(x[r][i]) sum++;
return sum;
} int GetColStoneNum(int x[][], int c)
{
int sum = ;
for(int i=; i<; i++) if(x[i][c]) sum++;
return sum;
} void show(int x[][])
{
for(int i=; i<; i++)
{
for(int j=; j<; j++) printf("%2d", x[i][j]);
printf("\n");
}
printf("\n");
} void f(int x[][], int r, int c); void GoNext(int x[][], int r, int c)
{
if(c<)
_______________________; // 填空
else
f(x, r+, );
} void f(int x[][], int r, int c)
{
if(r==)
{
if(CheckStoneNum(x))
{
N++;
show(x);
}
return;
} if(______________) // 已经放有了棋子
{
GoNext(x,r,c);
return;
} int rr = GetRowStoneNum(x,r);
int cc = GetColStoneNum(x,c); if(cc>=) // 本列已满
GoNext(x,r,c);
else if(rr>=) // 本行已满
f(x, r+, );
else
{
x[r][c] = ;
GoNext(x,r,c);
x[r][c] = ; if(!(-rr >= -c || -cc >= -r)) // 本行或本列严重缺子,则本格不能空着!
GoNext(x,r,c);
}
} int main(int argc, char* argv[])
{
int x[][] = {
{,,,,,},
{,,,,,},
{,,,,,},
{,,,,,},
{,,,,,},
{,,,,,}
}; f(x, , ); printf("%d\n", N); return ;
}
请分析代码逻辑,并推测划线处的代码。
答案写在 “解答.txt” 文件中
注意:只写划线处应该填的内容,划线前后的内容不要抄写。
解答:
NumRow!= || NumCol!=
f(x,r,c+)
x[r][c]==
测试代码:
#include <stdio.h> int N = ; bool CheckStoneNum(int x[][])
{
for(int k=; k<; k++)
{
int NumRow = ;
int NumCol = ;
for(int i=; i<; i++)
{
if(x[k][i]) NumRow++;
if(x[i][k]) NumCol++;
}
if(NumRow!=3 || NumCol!=3) return false; // 填空
}
return true;
} int GetRowStoneNum(int x[][], int r)
{
int sum = ;
for(int i=; i<; i++) if(x[r][i]) sum++;
return sum;
} int GetColStoneNum(int x[][], int c)
{
int sum = ;
for(int i=; i<; i++) if(x[i][c]) sum++;
return sum;
} void show(int x[][])
{
for(int i=; i<; i++)
{
for(int j=; j<; j++) printf("%2d", x[i][j]);
printf("\n");
}
printf("\n");
} void f(int x[][], int r, int c); void GoNext(int x[][], int r, int c)
{
if(c<)
f(x,r,c+1); // 填空
else
f(x, r+, );
} void f(int x[][], int r, int c)
{
if(r==)
{
if(CheckStoneNum(x))
{
N++;
show(x);
}
return;
} if(x[r][c]==1) // 已经放有了棋子
{
GoNext(x,r,c);
return;
} int rr = GetRowStoneNum(x,r);
int cc = GetColStoneNum(x,c); if(cc>=) // 本列已满
GoNext(x,r,c);
else if(rr>=) // 本行已满
f(x, r+, );
else
{
x[r][c] = ;
GoNext(x,r,c);
x[r][c] = ; if(!(-rr >= -c || -cc >= -r)) // 本行或本列严重缺子,则本格不能空着!
GoNext(x,r,c);
}
} int main(int argc, char* argv[])
{
int x[][] = {
{,,,,,},
{,,,,,},
{,,,,,},
{,,,,,},
{,,,,,},
{,,,,,}
}; f(x, , ); printf("%d\n", N); return ;
}
Freecode : www.cnblogs.com/yym2013