java—实现一个算法来检查非图解

agxfikkp  于 2021-07-12  发布在  Java
关注(0)|答案(1)|浏览(271)

我试着写一个算法来检查一个非图是否已经被解决了。我已经创建了多个类来拥有helper方法。到目前为止,我的设计是为 Clues 其中构造函数如下所示:

public Clues(int[][] rowClues, int[][] colClues) { // constructor stuff }

我把线索储存在二维阵列中。例如,这个拼图的线索存储方式如下:

int[][] rowClues =
    new int[][] {
      new int[] {0, 2},
      new int[] {1, 2},
      new int[] {0, 3},
      new int[] {0, 3},
      new int[] {1, 1},
    };

int[][] colClues =
    new int[][] {
      new int[] {1, 1},
      new int[] {0, 1},
      new int[] {0, 3},
      new int[] {0, 3},
      new int[] {3, 1},
    };

我创建了另一个类叫做 Puzzle 那是由一块棋盘(游戏用)和线索组成的。我正在尝试编写一个名为 isSolved 检查这个难题是否已经解决了,但我正在努力想出一个算法。我现在有:

public boolean isSolved() {

    boolean flag = false;
    for (int i=0; i<clue.getColCluesLength(); i++) {
      flag = checkColumn(getBoard().getBoardColumn(i), getClues().getColClues(i));
      if (flag == false) {
        return false;
      }
    }
    for (int i=0; i<clue.getRowCluesLength(); i++) {
      flag = checkRow(getBoard().getBoardRow(i), getClues().getRowClues(i));
      if (flag == false) {
        return false;
      }
    }
    return flag;
  }

  public boolean isRowSolved() {
    for (int i=0; i< clue.getRowCluesLength(); i++) {
      for (int j=0; j< clue.getRowClues(i).length; j++) {

      }
    }
    return false;
  }

我的电路板(2d数组)存储int,某些值表示消去、空格和着色。
我想我可以比较现有的阵列在董事会与线索阵列,但我不知道如何确切地做到这一点。
此部件的一些辅助方法包括: int[] getRowClues(int index) , int getColRowCluesLength() , int getWidth() (每行拼图中水平排列的单元格数), getBoard().isShaded() , getBoard().isEliminated() , getBoard().isSpace()

ssm49v7z

ssm49v7z1#

如果每一列和每一行都满足所有的线索,那么解决方案就是正确的。显然,正确的解决方案不能包含空白单元格,也就是说,单元格必须是阴影或消除。因此,要验证一个解决方案,必须遍历每一列和每一行,并检查线索是否满足要求。
一个小提示: isSolved() 方法可简化为:

public boolean isSolved(){
    return isRowSolved() && isColSolved();
}

现在要检查行或列,可以使用多种方法。这里有一个简单的方法,它基于一列构造一个新的“线索”,然后将这个新的线索与实际的线索进行比较。

private boolean checkColumn(int[] column, int[] clue){
  int count = 0; // Count sequence of shaded cells
  List<Integer> newClue=new LinkedList<>();
  for(int i=0; i<column.length; i++){
    if(column[i] == SHADED){ //Found a new shaded cell, increment counter
      count++;
    }else if(column[i] == ELIMINATED){ //Found a ELIMINATED cell. If counter >0, we completed a sequence
      if(count > 0){
        newClue.add(count);
        count=0; //Reset counter
      }
    }else{
      return false; //blank cell
    }
  }
  if(count > 0) //Remember to add the last one too
    newClue.add(count);

  //Finally, we can check whether the given clue matches the clue constructed from the column:
  int[] newClueArray = newClue.stream().mapToInt(i->i).toArray();
  return Arrays.equals(clue, newClueArray)
}

上面的方法返回 true 如果给定的列满足给定的线索, false 否则。如果列包含空白单元格,也会返回false。
注:我不知道一个非图形是否可以包含不包含任何阴影单元格的列(即所有单元格都被删除)。如果发生了这种情况,那么我认为这样一个专栏的线索是 new int[]{0} ,在这种情况下,您必须验证 newClue 在上面的示例中,代码是一个空列表。

相关问题