使用bfs宽度优先。
根据 leetCode的单词搜索题https://leetcode-cn.com/problems/word-search/得到思路。
class Solution {
public static void main(String[] args) {
char[][] migong =new char[][] {
{'s','#','#'},
{'.','.','.'},
{'.','.','e'}
};
new Solution().exist(migong,0,0,2,2);
System.out.println(lengthMax);
}
private static int length=0;
private static int lengthMax=Integer.MAX_VALUE;
/**
*
* @param board
* @param startI 起点
* @param startJ 起点
* @param endI 终点
* @param endJ 终点
* @return
*/
public boolean exist(char[][] board,int startI,int startJ,int endI,int endJ) {
int h = board.length, w = board[0].length;
// 用于表示走过的格子,就不能重复走
boolean[][] visited = new boolean[h][w];
boolean flag = check(board, visited, startI, startJ, endI,endJ);
if (flag) {
return true;
}
return false;
}
public boolean check(char[][] board, boolean[][] visited, int i,int j,int endI,int endJ) {
length++;
visited[i][j] = true;
int[][] directions = {{0, 1}, {0, -1}, {1, 0}, {-1, 0}};
boolean result = false;
for (int[] dir : directions) {
int newi = i + dir[0], newj = j + dir[1];
if (newi >= 0 && newi < board.length && newj >= 0 && newj < board[0].length
&& board[newi][newj]!='#') {
if (!visited[newi][newj]) {
if (newi==endI && newj==endJ) {
lengthMax = Math.min(length, lengthMax);
break;
}
boolean flag = check(board, visited, newi, newj, endI,endJ);
if (flag) {
result = true;
break;
}
}
}
}
visited[i][j] = false;
--length;
return result;
}
}