我使用了一种已知的算法来检查单词是否存在于网格中:
public boolean wordExists(String word, int row, int col) {
//all 8 directions
int[] x = { -1, -1, -1, 0, 0, 1, 1, 1 };
int[] y = { -1, 0, 1, -1, 1, -1, 0, 1 };
int rows = arrayLetters.length;
int cols = arrayLetters[0].length;
//Checking if the first character corresponds to the position row, col
if (arrayLetters[row][col] != word.charAt(0)) {
return false;
}
int lenWord = word.length();
//looping through all 8 directions
for (int direction = 0; direction < 8; direction++) {
int k = 0;
int dirRow = row + x[direction];
int dirCol = col + y[direction];
//Because the first character is checked we then check if the following characters
//correspond to the word
for (k = 1; k < lenWord; k++) {
//Out of bounds
if (dirRow >= rows || dirRow < 0 || dirCol >= cols|| dirCol < 0) {
break;
}
// If not matched
if (arrayLetters[dirRow][dirCol] != word.charAt(k)) {
break;
}
//If everything is valid move in that particular direction
dirRow += x[direction];
dirCol += y[direction];
}
//if word exists k should be equal to the length of the word
if (k == lenMot) {
return true;
}
}
//Otherwise
System.out.println("The word doesn't exist");
return false;
}
如果wordeexiststs返回true,则实际查找特定的单词,并考虑2d数组中每个可能的位置作为起点:
public void searchWord(String word) {
for (int row = 0; row < arrayLetters.length; row++) {
for (int col = 0; col < arrayLetters[0].length; col++) {
if (arrayLetters[row][col] == word.charAt(0) && wordExists(word, row, col)) {
System.out.println("Word position : " + row + ", " + col);
}
}
}
}
现在知道了这些,我如何用连字符替换匹配单词的字符?
有几种方法。一种简单的方法是传递一个数组或类似的东西给函数,然后用方向填充它。如果有匹配的单词,则传递包含所有方向的数组。但在没有匹配的情况下,只是返回空数组或不填充任何东西(假设你正在传递引用)。现在你可以很容易地编写另一个函数,甚至在同一个循环中,这样,给定起始的row
和col
,你只需遍历存储的方向,并用-
填充它们。
不张贴代码,因为它也张贴在algortihm
标签。冒昧地说出这个想法。