java - 有效地解决填字游戏

标签 java algorithm backtracking brute-force

<分区>

我有一个填字游戏和一个可用于解决它的单词列表(单词可以放置多次或什至一次)。对于给定的填字游戏和单词列表,总有一个解决方案。

我搜索了有关如何解决此问题的线索,发现它是 NP-Complete。我的最大填字游戏大小是 250 x 250,列表的最大长度(可用于解决它的单词数量)是 200。我的目标是通过蛮力/回溯来解决这种大小的填字游戏,这应该是可能的几秒钟(这是我的粗略估计,如果我错了请纠正我)。

例如:

可用于解决填字游戏的给定单词列表:

  • 可以
  • 音乐
  • 金枪鱼

给定的空填字游戏(X为不能填写的字段,空的字段需要填写):

An empty crossword which needs to be solved

解决方法:

The solution of the problem above

现在,我目前的方法是将填字游戏表示为二维数组并搜索空格(对填字游戏进行 2 次迭代)。然后我根据单词的长度将单词匹配到空格,然后我尝试将单词的所有组合都匹配到具有相同长度的空格。这种方法很快变得非常困惑,我在尝试实现它时迷路了,有没有更优雅的解决方案?

最佳答案

你的基本想法很合理:

  1. 识别板上的插槽。
  2. 用每个合适的单词尝试每个插槽。
  3. 如果每个插槽都可以无冲突地填充,则解决。

这是一个绝妙的计划。 下一步是将其转化为设计。 对于这样的小程序,我们可以直接使用伪代码。 正如其他答案所解释的那样,它的要点是 recursion :

1  Draw a slot from the slot pool.
2     If slot pool is empty (all slots filled), stop solving.
3  For each word with correct length:
4     If part of the slot is filled, check conflict.
5        If the word does not fit, continue the loop to next word.
      // No conflict
6     Fill the slot with the word.
      // Try next slot (down a level)
7     Recur from step 1.
8     If the recur found no solution, revert (take the word back) and try next.
   // None of them works
9  If no words yield a solution, an upper level need to try another word.
   Revert (put the slot back) and go back.

下面是我根据您的要求编写的一个简短但完整的示例。

There is more than one way to skin a cat. My code swapped step 1 and 2, and combines step 4 to 6 in one fill loop.

要点:

  • 使用格式化程序使代码适合您的风格。
  • 二维板存储在一个线性字符数组中row-major order .
  • 这允许板由clone() 保存并由arraycopy 恢复.
  • 在创建时,从两个方向分两次扫描电路板以寻找插槽。
  • 两个槽列表由同一个循环解决,主要区别在于槽的填充方式。
  • 显示重复过程,因此您可以看到它是如何工作的。
  • 做出了许多假设。没有单个字母槽,所有单词大小写相同,棋盘正确等。
  • 要有耐心。学习任何新事物,给自己时间吸收它。

来源:

import java.awt.Point;
import java.util.*;
import java.util.function.BiFunction;
import java.util.function.Supplier;
import java.util.stream.Stream;

public class Crossword {

   public static void main ( String[] args ) {
      new Crossword( Arrays.asList( "5 4 4\n#_#_#\n_____\n#_##_\n#_##_\ntuna\nmusic\ncan\nhi".split( "\n" ) ) );
      new Crossword( Arrays.asList( "6 6 4\n##_###\n#____#\n___#__\n#_##_#\n#____#\n##_###\nnice\npain\npal\nid".split( "\n" ) ) );
   }

   private final int height, width; // Board size
   private final char[] board; // Current board state.  _ is unfilled.  # is blocked.  other characters are filled.
   private final Set<String> words; // List of words
   private final Map<Point, Integer> vertical = new HashMap<>(), horizontal = new HashMap<>();  // Vertical and horizontal slots

   private String indent = ""; // For formatting log
   private void log ( String message, Object... args ) { System.out.println( indent + String.format( message, args ) ); }

   private Crossword ( List<String> lines ) {
      // Parse input data
      final int[] sizes = Stream.of( lines.get(0).split( "\\s+" ) ).mapToInt( Integer::parseInt ).toArray();
      width = sizes[0];  height = sizes[1];
      board = String.join( "", lines.subList( 1, height+1 ) ).toCharArray();
      words = new HashSet<>( lines.subList( height+1, lines.size() ) );
      // Find horizontal slots then vertical slots
      for ( int y = 0, size ; y < height ; y++ )
         for ( int x = 0 ; x < width-1 ; x++ )
            if ( isSpace( x, y ) && isSpace( x+1, y ) ) {
               for ( size = 2 ; x+size < width && isSpace( x+size, y ) ; size++ ); // Find slot size
               horizontal.put( new Point( x, y ), size );
               x += size; // Skip past this horizontal slot
            }
      for ( int x = 0, size ; x < width ; x++ )
         for ( int y = 0 ; y < height-1 ; y++ )
            if ( isSpace( x, y ) && isSpace( x, y+1 ) ) {
               for ( size = 2 ; y+size < height && isSpace( x, y+size ) ; size++ ); // Find slot size
               vertical.put( new Point( x, y ), size );
               y += size; // Skip past this vertical slot
            }
      log( "A " + width + "x" + height + " board, " + vertical.size() + " vertical, " + horizontal.size() + " horizontal." );
      // Solve the crossword, horizontal first then vertical
      final boolean solved = solveHorizontal();
      // Show board, either fully filled or totally empty.
      for ( int i = 0 ; i < board.length ; i++ ) {
         if ( i % width == 0 ) System.out.println();
         System.out.print( board[i] );
      }
      System.out.println( solved ? "\n" : "\nNo solution found\n" );
   }

   // Helper functions to check or set board cell
   private char get ( int x, int y ) { return board[ y * width + x ]; }
   private void set ( int x, int y, char character ) { board[ y * width + x ] = character; }
   private boolean isSpace ( int x, int y ) { return get( x, y ) == '_'; }

   // Fit all horizontal slots, when success move to solve vertical.
   private boolean solveHorizontal () {
      return solve( horizontal, this::fitHorizontal, "horizontally", this::solveVertical );
   }
   // Fit all vertical slots, report success when done
   private boolean solveVertical () {
      return solve( vertical, this::fitVertical, "vertically", () -> true );
   }

   // Recur each slot, try every word in a loop.  When all slots of this kind are filled successfully, run next stage.
   private boolean solve ( Map<Point, Integer> slot, BiFunction<Point, String, Boolean> fill, String dir, Supplier<Boolean> next ) {
      if ( slot.isEmpty() ) return next.get(); // If finished, move to next stage.
      final Point pos = slot.keySet().iterator().next();
      final int size = slot.remove( pos );
      final char[] state = board.clone();
      /* Try each word */                                                   indent += "  ";
      for ( String word : words ) {
         if ( word.length() != size ) continue;
         /* If the word fit, recur. If recur success, done! */              log( "Trying %s %s at %d,%d", word, dir, pos.x, pos.y );
         if ( fill.apply( pos, word ) && solve( slot, fill, dir, next ) )
            return true;
         /* Doesn't match. Restore board and try next word */               log( "%s failed %s at %d,%d", word, dir, pos.x, pos.y );
         System.arraycopy( state, 0, board, 0, board.length );
      }
      /* No match.  Restore slot and report failure */                      indent = indent.substring( 0, indent.length() - 2 );
      slot.put( pos, size );
      return false;
   }

   // Try fit a word to a slot.  Return false if there is a conflict.
   private boolean fitHorizontal ( Point pos, String word ) {
      final int x = pos.x, y = pos.y;
      for ( int i = 0 ; i < word.length() ; i++ ) {
         if ( ! isSpace( x+i, y ) && get( x+i, y ) != word.charAt( i ) ) return false; // Conflict
         set( x+i, y, word.charAt( i ) );
      }
      return true;
   }
   private boolean fitVertical ( Point pos, String word ) {
      final int x = pos.x, y = pos.y;
      for ( int i = 0 ; i < word.length() ; i++ ) {
         if ( ! isSpace( x, y+i ) && get( x, y+i ) != word.charAt( i ) ) return false; // Conflict
         set( x, y+i, word.charAt( i ) );
      }
      return true;
   }
}

Exercise: You can rewrite recursion to iteration; faster and can support bigger boards. Once that's done it can be converted to multi-thread and run even faster.

关于java - 有效地解决填字游戏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44606961/

相关文章:

Java - 使用 Wordnet 和 JWI 获取名词数组

java - 如何通过自定义 Web 应用程序连接到 Alfresco 文档

java - 当我在 jPA 中使用 persist() 时发生了什么

algorithm - 什么是用最少的重绘修改饼图的优化算法?

algorithm - 使用 32 位散列时发生冲突的概率

java - 最佳买卖股票修改版

java - 几乎相同的语句,但不同的值

java - 列表的 var 参数作为方法参数

ruby - 如何使具有回溯算法的数独求解器返回?

python迷宫使用递归