1.2 编写一个程序解决字谜游戏问题
package com.algorithm.chapterone;
import java.util.ArrayList;
import java.util.List;
/**
* 输入是由一些字母构成的一个二维数组以及一组单词组成。目标是要找出字谜中的单词, 这些单词可能是水平、垂直或者沿对角线任何方向放置的。
* @author Gao·Rongzheng
*
*/
public class QuestionTwo {
//※由字母构成的二维数组
private static char[][] letters = new char[][] {
{'t', 'h', 'i', 's'},
{'w', 'a', 't', 's'},
{'o', 'a', 'h', 'g'},
{'f', 'g', 'd', 't'}
};
//※目标单词数组
private static String[] words = {"this", "two", "fat", "that", "left"};
//※ 所有字符串的集合
private static List<String> stringList = new ArrayList<String>();
//※获取行,列,对角的最长字符串
//※获取所有最长字符串
public static void getStrings() {
StringBuilder sbRow = new StringBuilder();
StringBuilder sbCol = new StringBuilder();
StringBuilder sbLeftDiagonal = new StringBuilder();
StringBuilder sbRightDiagonal = new StringBuilder();
for (int i=0; i<letters.length; i++) {
sbRow.delete(0, sbRow.length());
sbCol.delete(0, sbRow.length());
//※获取左对角最长字符串
sbLeftDiagonal.append(letters[i][i]);
//※获取右对角最长字符串
sbRightDiagonal.append(letters[i][letters.length-i-1]);
for (int j=0; j<letters[i].length; j++) {
//※获取行最长字符串
sbRow.append(letters[i][j]);
//※获取列最长字符串
sbCol.append(letters[j][i]);
}
stringList.add(sbRow.toString());
stringList.add(sbRow.reverse().toString());
stringList.add(sbCol.toString());
stringList.add(sbCol.reverse().toString());
}
stringList.add(sbLeftDiagonal.toString());
stringList.add(sbLeftDiagonal.reverse().toString());
stringList.add(sbRightDiagonal.toString());
stringList.add(sbRightDiagonal.reverse().toString());
}
public static void main(String[] args) {
getStrings();
String[] allStrings = stringList.toArray(new String[stringList.size()]);
for (int i=0; i<words.length; i++) {
for (int j = 0; j < allStrings.length; j++) {
if (allStrings[j].contains(words[i])) {
System.out.println(words[i]);
break;
}
}
}
}
}