活跃农民
- 积分
- 353
- 大米
- 颗
- 鳄梨
- 个
- 水井
- 尺
- 蓝莓
- 颗
- 萝卜
- 根
- 小米
- 粒
- 学分
- 个
- 注册时间
- 2013-4-10
- 最后登录
- 1970-1-1
|
private static class Cell{
int x;
int y;
Set<List<Integer>> path;
private Cell(int x, int y) {
this.x = x;
this.y = y;
this.path = new LinkedHashSet<>();
}
}
public boolean findWord(char[][] matrix, String target) {
if (matrix == null || matrix.length == 0
|| matrix[0].length == 0 || target == null || target.length() == 0) {
return false;
}
int[][] dirs = new int[][] {{1,0},{-1,0},{0,1},{0,-1},{1,1},{-1, -1},{1, -1},{-1, 1}};
int row = matrix.length;
int col = matrix[0].length;
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
if (matrix[i][j] == target.charAt(0)) {
if (helper(matrix, i, j, dirs, target)) {
return true;
}
}
}
}
return false;
}
public boolean helper(char[][] matrix, int x, int y, int[][] dirs, String target) {
int row = matrix.length;
int col = matrix[0].length;
int step = 0;
Queue<Cell> queue = new LinkedList<>();
Cell first = new Cell(x, y);
first.path.add(Arrays.asList(x, y));
queue.add(first); // 没加进去
while (!queue.isEmpty()) {
Cell currCell = queue.poll();
step++;
if (step == target.length()) {
return true;
}
for (int[] dir : dirs) {
int nextX = currCell.x + dir[0];
int nextY = currCell.y + dir[1];
List<Integer> nextPos = Arrays.asList(nextX, nextY);
if (nextX >= 0 && nextX < row
&& nextY >= 0 && nextY < col
&& !currCell.path.contains(nextPos)
&& matrix[nextX][nextY] == target.charAt(step)) {
Cell newCell = new Cell(nextX, nextY);
newCell.path = new LinkedHashSet<>(currCell.path);
newCell.path.add(nextPos);
queue.offer(newCell);
}
}
}
return false;
} |
|