Maze

import java.util.*;

public class Maze {

    private final static int[] dx = {-1, 0, 0, 1};
    private final static int[] dy = {0, 1, -1, 0};

    public static void main(String[] args) {
        int[][] matrix = {
                {1,1,1,1,1},
                {1,1,0,1,1},
                {0,1,1,0,0},
                {1,0,1,1,0}
        };
        System.out.println(findPath(matrix));
    }


    public static int findPath(int[][] matrix) {

        if (matrix == null || matrix.length == 0 || matrix[0] == null || matrix[0].length == 0) {
            return 0;
        }
        if (matrix[0][0] == 0) {
            return 0;
        }
        if (matrix[0][0] == 9) {
            return 1;
        }
        int m = matrix.length, n = matrix[0].length;
        boolean[][] visited = new boolean[m][n];
        Queue<Point> queue = new LinkedList<>();
        queue.add(new Point(0, 0));

        while (!queue.isEmpty()) {
            Point cur = queue.poll();
            for (int i = 0; i < 4; i++) {
                int x = cur.x + dx[i];
                int y = cur.y + dy[i];
                if (x < 0 || x >= m || y < 0 || y >= n || visited[x][y] || matrix[x][y] == 0) continue; // over boundray skip
                if (matrix[x][y] == 9) {
                    return 1;
                } else if (matrix[x][y] == 1) {
                    visited[x][y] = true;
                    queue.add(new Point(x, y));
                }
            }
        }

        return 0;
    }

}

class Point {
    int x;
    int y;

    public Point(int x, int y) {
        this.x = x;
        this.y = y;
    }
}

results matching ""

    No results matching ""