Closed congr closed 5 years ago
class Solution {
class Point {
int x, y;
Point(int y, int x) {
this.y = y;
this.x = x;
}
}
int[] dy = {-1,0,1,0};
int[] dx = {0,-1,0,1};
public boolean hasPath(int[][] maze, int[] start, int[] destination) {
Queue<Point> q = new LinkedList();
q.add(new Point(start[0], start[1]));
boolean[][] visited = new boolean[maze.length][maze[0].length];
while(!q.isEmpty()) {
Point p = q.remove();
if (p.y == destination[0] && p.x == destination[1]) return true;
for (int d = 0; d < 4; d++) {
int nx = p.x + dx[d], ny = p.y + dy[d];
while (inside(ny, nx, maze) && maze[ny][nx] == 0) {
nx += dx[d];
ny += dy[d];
}
nx -= dx[d];
ny -= dy[d];
if (visited[ny][nx]) continue;
q.add(new Point(ny, nx));
visited[ny][nx] = true;
}
}
return false;
}
boolean inside(int y, int x, int[][] maze) {
if (y>=0 && x>=0 && y<maze.length && x<maze[0].length) return true;
return false;
}
}
https://leetcode.com/problems/the-maze/