|
| 1 | +package com.eprogrammerz.examples.algorithm.graphs; |
| 2 | + |
| 3 | +import java.util.LinkedList; |
| 4 | +import java.util.List; |
| 5 | +import java.util.Queue; |
| 6 | + |
| 7 | +/** |
| 8 | + * There is a rectangle with left bottom as (0, 0) and right up as (x, y). There are N circles such that their centers are inside the rectangle. |
| 9 | + * Radius of each circle is R. Now we need to find out if it is possible that we can move from (0, 0) to (x, y) without touching any circle. |
| 10 | + * <p> |
| 11 | + * Note : We can move from any cell to any of its 8 adjecent neighbours and we cannot move outside the boundary of the rectangle at any point of time. |
| 12 | + */ |
| 13 | +public class ValidPath { |
| 14 | + public String solve(int tx, int ty, int n, int r, List<Integer> cx, List<Integer> cy) { |
| 15 | + int[] dx = {1, 0, -1, -1, -1, 0, 1, 1}; |
| 16 | + int[] dy = {-1, -1, -1, 0, 1, 1, 1, 0}; |
| 17 | + Queue<int[]> queue = new LinkedList<>(); |
| 18 | + queue.add(new int[]{0, 0}); |
| 19 | + |
| 20 | + boolean[][] visited = new boolean[tx + 1][ty + 1]; |
| 21 | + |
| 22 | + while (!queue.isEmpty()) { |
| 23 | + int[] cell = queue.poll(); |
| 24 | + int x = cell[0]; |
| 25 | + int y = cell[1]; |
| 26 | + visited[x][y] = true; |
| 27 | + |
| 28 | + if (x == tx && y == ty) return "YES"; |
| 29 | + |
| 30 | + for (int i = 0; i < 8; i++) { |
| 31 | + x = x + dx[i]; |
| 32 | + y = y + dy[i]; |
| 33 | + |
| 34 | + if (isValid(x, y, tx, ty, n, r, cx, cy) && !visited[x][y]) { |
| 35 | + queue.add(new int[]{x, y}); |
| 36 | + } |
| 37 | + } |
| 38 | + } |
| 39 | + return "NO"; |
| 40 | + } |
| 41 | + |
| 42 | + private boolean isValid(int x, int y, int tx, int ty, int n, int r, List<Integer> cx, List<Integer> cy) { |
| 43 | + if (x < 0 || y < 0 || x > tx || y > ty) return false; |
| 44 | + |
| 45 | + // check if (x,y) falls in one of the circle |
| 46 | + for (int i = 0; i < n; i++) { |
| 47 | + int centerX = cx.get(i); |
| 48 | + int centerY = cy.get(i); |
| 49 | + |
| 50 | + if (Math.sqrt(Math.pow(x - centerX, 2) + Math.pow(y - centerY, 2)) <= r) { |
| 51 | + return false; |
| 52 | + } |
| 53 | + |
| 54 | + } |
| 55 | + |
| 56 | + return true; |
| 57 | + } |
| 58 | +} |
0 commit comments