0

我错过了这项任务的最后期限,但仍然困扰着我,我不明白我在为这个项目做什么。它是数独解决方案检查器的第 2 部分,需要添加四种方法,它们是

public boolean checkAndPrintReport( ) {*/return true;}

它应该检查所有失败的行或列的所有行或打印行。其他的是

public boolean isGoodRow( int yRowParam ) {return true;}
public boolean isGoodColumn( int xColParam ) {return true;}
public boolean isGoodBlock(int xBlockP, int yBlockP) {return true;} 

最后,我的 checkAll() 方法应该有三个嵌套循环,每个循环调用上述三个 9 次。

我不明白这部分需要什么,因为我认为我已经在这里编写了一个解决方案检查器

public int timesRowHas( int yParam, int number ) { 
    int nTimesHas = 0;
    for( int x = 0; x < 9; x++ )
        if( this.getCell(x, yParam) == number )
            nTimesHas = nTimesHas + 1;

    return( nTimesHas );
}

public int timesColHas( int xParam, int number ) {
    int nTimesHas = 0;
    for( int y = 0; y < 9; y++ )
        if( this.getCell(xParam, y) == number )
            nTimesHas = nTimesHas + 1;

    return( nTimesHas );
}

public int timesBlockHas( int xBlockParam, int yBlockParam, int number ) {
    if( xBlockParam < 0 || xBlockParam > 2 || yBlockParam < 0 || yBlockParam > 2 )
        throw new IllegalArgumentException("Bad xBlockParam or bad yBlockParam or both..");

    int nTimesHas = 0; 
    for (int x=0; x<3; x++)
        for (int y=0; y<3;y++)
            nTimesHas = nTimesHas +getCell(xBlockParam+x, yBlockParam+y);

    return(nTimesHas);
 }
4

1 回答 1

0

您编写的函数并不完全符合您的需要。您的函数仅检查单个数字连续出现的次数(列或框)。

要判断一行(列或框)是否良好,您确实需要检查所有数字(1-9),而不仅仅是其中一个。

但是,好消息是您可以使用您的函数实现所需的函数:

public boolean isGoodRow( int yRowParam ){
    // for number = 1,..,9, ensure the count is not > 1
    for(int i=1; i<=9; i++)
        if(timesRowHas(yRowParam, i) > 1)
            return false;
    return true;
}

(如果您有兴趣):这不是最有效的解决方案,它在 O(n 2 ) 时间内运行。通过对行中的 # 进行直方图,可以在 O(n) 时间内找到 isGoodRow()。


一旦你实现了必要的功能:

public boolean isGoodRow( int yRowParam )
public boolean isGoodColumn( int xColParam )
public boolean isGoodBlock(int xBlockP, int yBlockP)

然后你只需要使用它们来实现checkAndPrintReport()

public boolean checkAndPrintReport(){ 
   for(int i=0; i<9; i++)
        if(!isGoodRow(i) || !isGoodColumn(i) || !isGoodBlock(i/3, i%3)
            return false;
   return true;
}
于 2013-12-04T05:11:25.350 回答