我已经实现了一个简单的广度优先搜索算法(bfs),每次搜索时,将要查找的字符串 toFind(在这种情况下是 AMAZON)的第一个字符与二维数组中的字符进行匹配。使用了一个简单的 visited 二维数组,在一次迭代中检查标记的字符:
public class FindStrings {
private static int count = 0;
public static void find(Character[][] a, String toFind) {
int rows = a.length;
int col = a[0].length;
boolean[][] visited = new boolean[a.length][a[0].length];
for (int i = 0; i < rows; i++) {
for (int j = 0; j < col; j++) {
if (a[i][j] == toFind.charAt(0)) {
findUtil(visited, a, i, j, 0, toFind, new StringBuilder(), rows - 1, col - 1,new ArrayList<String>());
visited[i][j] = false;
}
}
}
}
private static void findUtil(boolean[][] visited, Character[][] a, int i, int j, int index, String toFind, StringBuilder result, int R, int C,ArrayList<String> list) {
result.append(a[i][j]);
list.add(i+"-"+j);
if (index == toFind.length() - 1 && result.toString().equals(toFind)) {
System.out.println(list.toString());
count++;
return;
}
visited[i][j] = true;
int nextIndex = index + 1;
int nextR, nextC;
if (i + 1 >= 0 && j >= 0 && i + 1 <= R && j <= C && !visited[i + 1][j] && a[i + 1][j] == toFind.charAt(nextIndex)) {
nextR = i + 1;
nextC = j;
findUtil(visited, a, nextR, nextC, nextIndex, toFind, new StringBuilder(result), R, C,new ArrayList<>(list));
visited[nextR][nextC] = false;
}
if (i >= 0 && j + 1 >= 0 && i <= R && j + 1 <= C && !visited[i][j + 1] && a[i][j + 1] == toFind.charAt(nextIndex)) {
nextR = i;
nextC = j + 1;
findUtil(visited, a, nextR, nextC, nextIndex, toFind, new StringBuilder(result), R, C,new ArrayList<>(list));
visited[nextR][nextC] = false;
}
if (i >= 0 && j - 1 >= 0 && i <= R && j - 1 <= C && !visited[i][j - 1] && a[i][j - 1] == toFind.charAt(nextIndex)) {
nextR = i;
nextC = j - 1;
findUtil(visited, a, nextR, nextC, nextIndex, toFind, new StringBuilder(result), R, C,new ArrayList<>(list));
visited[nextR][nextC] = false;
}
if (i - 1 >= 0 && j >= 0 && i - 1 <= R && j <= C && !visited[i - 1][j] && a[i - 1][j] == toFind.charAt(nextIndex)) {
nextR = i - 1;
nextC = j;
findUtil(visited, a, nextR, nextC, nextIndex, toFind, new StringBuilder(result), R, C,new ArrayList<>(list));
visited[nextR][nextC] = false;
}
}
public static int getCount() {
return count;
}
public static void main(String[] args) {
Character[][] a = new Character[][]{
{'B', 'B', 'A', 'B', 'B', 'N'},
{'B', 'B', 'M', 'B', 'B', 'O'},
{'B', 'B', 'A', 'B', 'B', 'Z'},
{'B', 'O', 'Z', 'O', 'N', 'A'},
{'B', 'B', 'O', 'Z', 'B', 'M'},
{'B', 'B', 'N', 'A', 'M', 'A'}
};
String toFind = "AMAZON";
find(a, toFind);
System.out.println(getCount());
}