本身寫的一個findWords方法,傳入一個單詞testStr,根據二維數組橫縱及斜線相鄰字符找這個單詞,若存在則返回true
public class test {
public static void main(String[] args) {
// TODO Auto-generated method stub
//System.out.println(test.findWords("JD"));
//System.out.println(test.findWords("YOF"));
//System.out.println(test.findWords("DAU"));
//System.out.println(test.findWords("QFAE"));
System.out.println(test.findWords("ODERF"));
System.out.println(test.findWords("UUQSE"));
System.out.println(test.findWords("BZQ"));
//System.out.println(test.findWords("XD"));
}
public static boolean findWords (String testStr){
char[][] grid = new char[][] {
{'H','M','Z','Y','U','Y','J','X'},
{'S','X','A','H','E','A','O','D'},
{'C','U','B','N','V','A','D','F'},
{'O','Y','B','A','F','S','F','E'},
{'M','A','S','T','E','R','S','Q'},
{'P','R','D','G','E','Q','E','Q'},
{'U','R','K','D','U','O','Z','D'},
{'T','A','O','U','I','B','X','Y'}
};
StringBuffer sb=new StringBuffer(testStr);
sb.reverse();
//行
String row="";
String col="";
for(int i=0;i<grid.length;i++){
for(int j=0;j<grid[0].length;j++){
row+=grid[i][j];
}
for(int j=0;j<grid[0].length+1-testStr.length();j++){
if(row.substring(j, j+testStr.length()).equals(testStr)||row.substring(j, j+testStr.length()).equals(sb.toString())){
return true;
}
}
row="";
}
//列
for(int i=0;i<grid[0].length;i++){
for(int j=0;j<grid.length;j++){
col+=grid[j][i];
}
for(int j=0;j<grid[0].length+1-testStr.length();j++){
if(col.substring(j, j+testStr.length()).equals(testStr)||col.substring(j, j+testStr.length()).equals(sb.toString())){
return true;
}
}
col="";
}
//對角線
String str1="";
String str2="";
//左斜線 i>j
for(int i=1;i<grid.length;i++){
for(int j=0;j<=i;j++){
str1+=grid[i-j][j];
}
for(int j=0;j<str1.length()+1-testStr.length();j++){
if(str1.substring(j, j+testStr.length()).equals(testStr)||str1.substring(j, j+testStr.length()).equals(sb.toString())){
return true;
}
}
str1="";
}
for(int i=0;i<grid.length-1;i++){
for(int j=0;j<=grid.length-i-1;j++){
str1+=grid[i+j][j];
}
for(int j=0;j<str1.length()+1-testStr.length();j++){
if(str1.substring(j, j+testStr.length()).equals(testStr)||str1.substring(j, j+testStr.length()).equals(sb.toString())){
return true;
}
}
str1="";
}
//右斜線
for(int i=1;i<grid.length;i++){
for(int j=0;j<=i;j++){
str2+=grid[i-j][grid.length-j-1];
}
for(int j=0;j<str2.length()+1-testStr.length();j++){
if(str2.substring(j, j+testStr.length()).equals(testStr)||str2.substring(j, j+testStr.length()).equals(sb.toString())){
return true;
}
}
str2="";
}
for(int i=0;i<grid.length-1;i++){
for(int j=0;j<grid.length-i;j++){
str2+=grid[i+j][grid.length-j-1];
}
for(int j=0;j<str2.length()+1-testStr.length();j++){
if(str2.substring(j, j+testStr.length()).equals(testStr)||str2.substring(j, j+testStr.length()).equals(sb.toString())){
return true;
}
}
str2="";
}
return false;
}
}
數組