您的基本想法非常明智:
1.识别板上的插槽。
2.尝试每个适合的单词插入每个插槽。
3.如果可以填充每个插槽而不冲突,则解决了问题。
这是一个很好的计划。下一步是将其转化为设计。对于像这样的小程序,我们可以直接使用伪代码。正如其他答案所解释的那样,它的要点是
递归:
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.
以下是我根据您的需求编写的一个简短但完整的示例。
有多种方法可以解决问题。
我的代码交换了步骤1和2,并将步骤4到6合并为一个填充循环。
要点:
- 使用格式化程序来适应您的代码风格。
- 2D棋盘以行主序的方式存储在线性字符数组中。
- 这使得棋盘可以通过
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;
private final char[] board;
private final Set<String> words;
private final Map<Point, Integer> vertical = new HashMap<>(), horizontal = new HashMap<>();
private String indent = "";
private void log ( String message, Object... args ) { System.out.println( indent + String.format( message, args ) ); }
private Crossword ( List<String> lines ) {
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() ) );
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++ );
horizontal.put( new Point( x, y ), size );
x += size;
}
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++ );
vertical.put( new Point( x, y ), size );
y += size;
}
log( "A " + width + "x" + height + " board, " + vertical.size() + " vertical, " + horizontal.size() + " horizontal." );
final boolean solved = solveHorizontal();
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" );
}
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 ) == '_'; }
private boolean solveHorizontal () {
return solve( horizontal, this::fitHorizontal, "horizontally", this::solveVertical );
}
private boolean solveVertical () {
return solve( vertical, this::fitVertical, "vertically", () -> true );
}
private boolean solve ( Map<Point, Integer> slot, BiFunction<Point, String, Boolean> fill, String dir, Supplier<Boolean> next ) {
if ( slot.isEmpty() ) return next.get();
final Point pos = slot.keySet().iterator().next();
final int size = slot.remove( pos );
final char[] state = board.clone();
indent += " ";
for ( String word : words ) {
if ( word.length() != size ) continue;
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;
log( "%s failed %s at %d,%d", word, dir, pos.x, pos.y );
System.arraycopy( state, 0, board, 0, board.length );
}
indent = indent.substring( 0, indent.length() - 2 );
slot.put( pos, size );
return false;
}
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;
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;
set( x, y+i, word.charAt( i ) );
}
return true;
}
}
练习:您可以重写递归为迭代;更快且可以支持更大的棋盘。一旦完成,它可以转换为多线程并运行得更快。