【发布时间】:2020-04-17 07:40:01
【问题描述】:
所以我正在尝试创建一个新对象以添加到列表中
public void findWord(char boggle[][], boolean visited[][], int i,
int j, String str)
{
visited[i][j] = true;
str = str + boggle[i][j];
if (hasWord(str)) {
for (char c : str.toCharArray()) {
Position<Character> pos = new Position<>(c, i, j);
list.add(pos);
}
}
for (int row = i - 1; row <= i + 1 && row < 4; row++)
for (int column = j - 1; column <= j + 1 && column < 4; column++)
if (row >= 0 && column >= 0 && !visited[row][column])
findWord(boggle, visited, row, column, str);
visited[i][j] = false;
}
问题是基本上每个位置(行和列)都被覆盖到该对象的最后一个创建实例,但元素本身不是。
我的职位类别:
public class Position<T> {
private T element;
private int row;
private int column;
Position () {
this(null,0,0);
}
Position (T element) {
this.element = element;
}
Position (T element, int row, int column) {
this.element = element;
this.row = row;
this.column = column;
}
public int getRow() {
return row;
}
public int getColumn() {
return column;
}
public T getElement() {
return element;
}
public String toString() {
return element + "(" + Integer.toString(row) + "," + column + ")";
}
也就是说,我打印后的 List 输出类似于:
a(2,2) a(2,2) r(2,2) o(2,2) n(2,2)
最后一个位置在元素和索引中都是正确的,但在矩阵索引中所有其他位置都失败了。应该是:
a(0,0) a(1,0) r(1,1) o(1,2) n(2,2)
孔类:
import java.io.*;
public class Boogle {
LinkedList<Position<Character>> list = new LinkedList<>();
static QuadHashTable<String> table = new QuadHashTable<>();
String word;
static char matrix [] [] = {
{'a', '-', '-', '-'},
{'a', 'r', 'o', '-'},
{'-', '-', 'n', '-'},
{'-', '-', '-', '-'}
};
public Boogle () {
this(null);
}
public Boogle (char matrix [] []) {
this.matrix = matrix;
}
public boolean hasWord (String s) {
return s.equals(table.search(s));
}
public void findWordsUtil(char boggle[][], boolean visited[][], int i,
int j, String str)
{
visited[i][j] = true;
str = str + boggle[i][j];
if (hasWord(str))
for (char c : str.toCharArray()) {
Position<Character> pos = new Position<>(c, i, j);
list.add(pos);
}
for (int row = i - 1; row <= i + 1 && row < 4; row++)
for (int column = j - 1; column <= j + 1 && column < 4; column++)
if (row >= 0 && col >= 0 && !visited[row][column])
findWordsUtil(boggle, visited, row, column, str);
visited[i][j] = false;
}
public LinkedList<Position<Character>> solve () {
String s = "";
boolean visited[][] = new boolean[4][4];
String str = "";
for (int i = 0; i < 4; i++)
for (int j = 0; j < 4; j++)
findWordsUtil(matrix, visited, i, j, str);
return list;
}
public static void main (String args []) throws IOException {
BufferedReader br = new BufferedReader(new FileReader("/home/dsolipa/Desktop/allWords.txt"));
String line;
while((line = br.readLine()) != null) {
table.insert(line);
}
Boogle boogle = new Boogle(matrix);
System.out.println(boogle.solve());
//System.out.println(boogle.hasWord("or"));
}
}
【问题讨论】:
-
在 for-each 循环之外定义
Position<Character> pos = new Position<>(c, i, j);。 -
我也遇到了同样的问题。不过谢谢!
-
请发布所有代码
-
缺少什么/不需要在那里?抱歉所有菜鸟问题-_-
标签: java loops object recursion