今天我学会了在java中编写代码拼图单词。我强调列表中的搜索词,我只想搜索它(垂直,水平)而不是对角线。我的代码没有给我错误和结果。你能帮我刷一下吗?
public class WordPuzzle {
private final String puzzleString[][];
private final int rowNumber;
public WordPuzzle(String[][] puzzleString,int rowNumber){
this.puzzleString=puzzleString;
this.rowNumber=rowNumber;
}
public void showPuzzle(){
for(int i=0;i<rowNumber;i++){
for(int j=0;j<rowNumber;j++){
System.out.print(" "+puzzleString[i][j]);
}
System.out.println();
}
}
public Set<String> searchWord(Set<String> word){
Set<String> foundWord=new HashSet<String>();
int minimumWordLength=findMinimumWordLenght(word);
Set<String>compWord=CompatitableWord(minimumWordLength);
for(String w:word){
for(String posibleWord:compWord){
if(posibleWord.contains(w) || posibleWord.contains(new StringBuffer(w).reverse())){
foundWord.add(w);
break;
}
}
}
return foundWord;
}
private int findMinimumWordLenght(Set<String> wordLength){
int minimumLenght=Integer.MAX_VALUE;
for(String w:wordLength){
if(w.length()<minimumLenght){
minimumLenght=w.length();
}
}
return minimumLenght;
}
private Set<String> CompatitableWord(int minimumWordLength){
Set<String>compWord=new LinkedHashSet<String>();
int puzzleLength=puzzleString.length;
if(puzzleLength>=minimumWordLength){
for(int i=0;i<puzzleLength;i++){
if(puzzleString[i].length>=minimumWordLength){
compWord.add(new String(puzzleString[i].toString()));
}
}
for(int i=0;i<puzzleLength;i++){
StringBuffer tmp=new StringBuffer();
for(int j=0;j<puzzleLength;j++){
tmp=tmp.append(puzzleString[j][i]);
}
compWord.add(new String(tmp));
}
}
return compWord;
}
public static void main(String[] args){
String[][] a={{"g","y","r","a","r","b","i","l","e"},
{"u","a","a","n","c","h","o","r","i"},
{"i","b","y","d","v","e","x","t","r"},
{"t","z","c","h","y","n","e","q","u"},
{"a","m","a","n","g","o","d","v","q"},
{"r","n","i","h","p","l","o","d","l"},
{"f","o","r","e","s","t","u","d","y"},
{"j","d","l","w","a","r","c","h","u"},
{"h","a","v","g","h","y","e","t","y"}
};
WordPuzzle pn=new WordPuzzle(a,9);
pn.showPuzzle();
Set<String> str=new HashSet<String>();
str.add("library");
Set<String>wordFound=pn.searchWord(str);
for(String w:wordFound){
System.out.println("Found"+pn.searchWord(str));
}
}
}
答案 0 :(得分:0)
你可以重写你的程序,因为它太复杂了。首先,将字符串替换为字符:您应该使用char的矩阵char[][] mat
。其次,将所有行和列保存到String
:
String[] rows = ... // use new String(mat[i])
String[] columns = ... // transform matrix and see solution for rows
在此之后,请使用rows[i].indexOf
或columns[i].indexOf
。
此外,您可以使用rows[i].reverse().indexOf
或columns[i].reverse().indexOf
。
抱歉我的英文不好