要求輸入的單詞的字符之間在數組裏面是鄰接關係
例如 :輸入二維字符矩陣如下:
A H E L
K M O L
H B W P
查找HELLOW明顯可以找到,對應的座標爲(0,1)——>(0,2)——>(0,3)——>(1,3)——>(1,2)——>(2,2),相當於一筆畫成HELLOW!
本題採用枚舉法實現。動態查找每一位的鄰接是否滿足條件,適當的剪枝是必要的!
轉載時請註明來源:http://blog.csdn.net/ccfeng2008
JAVA源碼如下(沒有對輸入數據進行合法性的檢查!):
package com;
public class SearchWord {
public static void main(String[] args) {
String[] a = { "hello2rt", "orow -=!","xldpoiyx","uu!yuuzz" };
System.out.println(isWord(a, "hello world!"));
}
public static boolean isWord(String[] matrix, String word) {
boolean ok = false;
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[i].length(); j++) {
ok = dfs(0, matrix, word, i, j);
if (ok) break;
}
if (ok) break;
}
return ok;
}
public static boolean dfs(int index, String[] matrix, String word, int i,
int j) {
if (index >= word.length())
return false;
if (!(i >= 0 && i < matrix.length && j >= 0 && j < matrix[i].length()))
return false;
char cur = word.charAt(index);
if (cur == matrix[i].charAt(j) && (index + 1) == word.length())
return true;
if (cur == matrix[i].charAt(j)) {
if (dfs(index + 1, matrix, word, i - 1, j))
return true;
if (dfs(index + 1, matrix, word, i + 1, j))
return true;
if (dfs(index + 1, matrix, word, i, j - 1))
return true;
if (dfs(index + 1, matrix, word, i, j + 1))
return true;
}
return false;
}
}
轉載時請註明來源:http://blog.csdn.net/ccfeng2008