|
| 1 | +package com.fishercoder.solutions; |
| 2 | + |
| 3 | +/** |
| 4 | + * 1401. Circle and Rectangle Overlapping |
| 5 | + * |
| 6 | + * Given a circle represented as (radius, x_center, y_center) and an axis-aligned rectangle represented as (x1, y1, x2, y2), where (x1, y1) are the coordinates of the bottom-left corner, and (x2, y2) are the coordinates of the top-right corner of the rectangle. |
| 7 | + * Return True if the circle and rectangle are overlapped otherwise return False. |
| 8 | + * In other words, check if there are any point (xi, yi) such that belongs to the circle and the rectangle at the same time. |
| 9 | + * |
| 10 | + * Example 1: |
| 11 | + * Input: radius = 1, x_center = 0, y_center = 0, x1 = 1, y1 = -1, x2 = 3, y2 = 1 |
| 12 | + * Output: true |
| 13 | + * Explanation: Circle and rectangle share the point (1,0) |
| 14 | + * |
| 15 | + * Example 2: |
| 16 | + * Input: radius = 1, x_center = 0, y_center = 0, x1 = -1, y1 = 0, x2 = 0, y2 = 1 |
| 17 | + * Output: true |
| 18 | + * |
| 19 | + * Example 3: |
| 20 | + * Input: radius = 1, x_center = 1, y_center = 1, x1 = -3, y1 = -3, x2 = 3, y2 = 3 |
| 21 | + * Output: true |
| 22 | + * |
| 23 | + * Example 4: |
| 24 | + * Input: radius = 1, x_center = 1, y_center = 1, x1 = 1, y1 = -3, x2 = 2, y2 = -1 |
| 25 | + * Output: false |
| 26 | + * |
| 27 | + * Constraints: |
| 28 | + * 1 <= radius <= 2000 |
| 29 | + * -10^4 <= x_center, y_center, x1, y1, x2, y2 <= 10^4 |
| 30 | + * x1 < x2 |
| 31 | + * y1 < y2 |
| 32 | + * */ |
| 33 | +public class _1401 { |
| 34 | + public static class Solution1 { |
| 35 | + public boolean checkOverlap(int radius, int xCenter, int yCenter, int x1, int y1, int x2, int y2) { |
| 36 | + if (x1 <= xCenter && x2 >= xCenter && y1 <= yCenter && y2 >= yCenter) { |
| 37 | + return true; |
| 38 | + } |
| 39 | + int circleDistance = radius * radius; |
| 40 | + for (int x = x1; x <= x2; x++) { |
| 41 | + if (dist(x, y1, xCenter, yCenter) <= circleDistance) { |
| 42 | + return true; |
| 43 | + } |
| 44 | + } |
| 45 | + |
| 46 | + for (int x = x1; x <= x2; x++) { |
| 47 | + if (dist(x, y2, xCenter, yCenter) <= circleDistance) { |
| 48 | + return true; |
| 49 | + } |
| 50 | + } |
| 51 | + |
| 52 | + for (int y = y1; y <= y2; y++) { |
| 53 | + if (dist(x1, y, xCenter, yCenter) <= circleDistance) { |
| 54 | + return true; |
| 55 | + } |
| 56 | + } |
| 57 | + |
| 58 | + for (int y = y1; y <= y2; y++) { |
| 59 | + if (dist(x2, y, xCenter, yCenter) <= circleDistance) { |
| 60 | + return true; |
| 61 | + } |
| 62 | + } |
| 63 | + return false; |
| 64 | + } |
| 65 | + |
| 66 | + private int dist(int x1, int y1, int x2, int y2) { |
| 67 | + return (x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2); |
| 68 | + } |
| 69 | + } |
| 70 | +} |
0 commit comments