我试图弄清楚如何在我自己的Java中创建一个拼图求解器但是卡住了。我能够读取文件的输入,其中填字游戏的尺寸存储在一个数组中。我在搜索实际拼图中的单词时遇到问题。这就是我到目前为止所做的:
package crossWrdNMaze2;
import java.io.File;
import java.util.Scanner;
public class crossWord {
public static void main(String[] args) throws Exception {
Scanner sc = new Scanner(new File("puzzle.txt"));
//r and c describe the dimensions of the puzzle array
int r = sc.nextInt();
int c = sc.nextInt();
char[][] array = new char[r][c];
//to scan puzzle chars into two-dimensional array
for (int i = 0; i<r; i++){
String getChar = new String(sc.next());
for(int j=0; j<c; j++){
array[i][j] = getChar.charAt(j);
}//end for2
}//end for1
//Test to make sure array was filled
for(int i=0; i<r; i++){
for(int j=0;j<r;j++)
System.out.print(array[i][j]);
System.out.println("");
}//end for
//scan in the number of words to be found in array (these integers follow the lines of
//letters which make up the array in the text file
int num = sc.nextInt();
System.out.println(num);
for(int i=0; i<num; i++){
//scan in the first word to be found
String getWord = new String(sc.next());
//determine word length to find size of array to look for in puzzle
int z = getWord.length();
char array2[] = new char[z];
//scan new string (word we are looking for) into an array so we can look for one letter
//at time in puzzle
for(int j=0; j<z;j++){
array2[j] = getWord.charAt(j);
}//end for2
//Size two array for the purpose of passing by reference so we can get coordinates of
//word in puzzle
int[] result = new int[1];
//pass array(puzzle), array2(word we are looking for), result(coordinates of word in array),
//r(number of rows in puzzle), c (number of columns in puzzle), z (length of word we
//are searching for)
findWord(array, array2, result, r, c, z);
//print loaction of word each time through loop
System.out.println(getWord + " is located at position (" + result[0] + ") (" + result[1] + ")");
}//end for1
sc.close();
}//end main
static void findWord(char arr1[][], char arr2[], int[] result, int a, int b, int c){
for(int i=0; i<a;i++){
for(int j=0; i<b;j++){
for(int k = 0; k<c;k++){
if(arr1[i][j] != arr2[k]){
System.out.println("Word not found!");//test to see if comparing letters and giving false return
}else if(arr1[i][j]== arr2[k]){
System.out.println("progress");//test to check if returning true when correct
}//end if
}//end for3
}//end fosr2
}//end for1
}//end function
}//end class
编辑:我在代码中添加了一些评论,我也记得最近我读过的一篇文章 生日快乐堆栈溢出,我是一个很长时间的读者,但这是我第一次发布。 再次感谢您的时间
答案 0 :(得分:0)
您可以构建问题的一种方法是将行,列和最终的对角条带提取到字符串(或字符数组)中,并针对该字符串执行测试。
for (int row=0; row<rows; row++) {
String strip=extractRow(row, arr);
if (strip.contains(word)) { ... }
}
for (int col=0; col<cols; col++) {
String strip=extractCol(col, arr);
if (strip.contains(word)) { ... }
}
如果你只是专注于提取你想要比较你的单词的字符序列,它将使你的问题更容易管理。