我需要解决一个填字游戏的问题,给定初始网格和单词(单词可以重复使用或者不使用)。
初始网格如下:
++_+++
+____+
___+__
+_++_+
+____+
++_+++
以下是一个单词列表的例子:
pain
nice
pal
id
任务是填充占位符 (水平或垂直,长度> 1),如下:
++p+++
+pain+
pal+id
+i++c+
+nice+
++d+++
任何正确的解决方案都可以接受,且有解决方案的保证。
为了开始解决问题,我将网格存储在二维字符数组中,并按其长度将单词存储在集合列表中:
List<Set<String>> words
,例如长度为4的单词可以通过words.get(4)
访问。然后,我提取网格中所有占位符的位置并将它们添加到占位符列表(堆栈)中:
class Placeholder {
int x, y; //coordinates
int l; // the length
boolean h; //horizontal or not
public Placeholder(int x, int y, int l, boolean h) {
this.x = x;
this.y = y;
this.l = l;
this.h = h;
}
}
算法的主要部分是solve()
方法:
char[][] solve (char[][] c, Stack<Placeholder> placeholders) {
if (placeholders.isEmpty())
return c;
Placeholder pl = placeholders.pop();
for (String word : words.get(pl.l)) {
char[][] possibleC = fill(c, word, pl); // description below
if (possibleC != null) {
char[][] ret = solve(possibleC, placeholders);
if (ret != null)
return ret;
}
}
return null;
}
fill(c, word, pl)
函数只是将当前单词写在当前占位符pl上,并返回一个新的填字游戏。如果word与pl不兼容,则函数返回null。
char[][] fill (char[][] c, String word, Placeholder pl) {
if (pl.h) {
for (int i = pl.x; i < pl.x + pl.l; i++)
if (c[pl.y][i] != '_' && c[pl.y][i] != word.charAt(i - pl.x))
return null;
for (int i = pl.x; i < pl.x + pl.l; i++)
c[pl.y][i] = word.charAt(i - pl.x);
return c;
} else {
for (int i = pl.y; i < pl.y + pl.l; i++)
if (c[i][pl.x] != '_' && c[i][pl.x] != word.charAt(i - pl.y))
return null;
for (int i = pl.y; i < pl.y + pl.l; i++)
c[i][pl.x] = word.charAt(i - pl.y);
return c;
}
}
这里是在Rextester上的完整代码。
问题在于我的回溯算法效果不佳。假设这是我的初始网格:
++++++
+____+
++++_+
++++_+
++++_+
++++++
以下是单词列表:
pain
nice
我的算法会将单词 pain
垂直放置,但意识到这是错误的选择后会回溯,但此时初始网格已经改变,占位符的数量也会减少。你认为该如何修复算法?