Count Lattice Points Inside a Circle - Brute Force & Euclidean Distance [JS]

Description 

Solution: Brute Force & Euclidean Distance

  1. Get the maximum x and y coordinate on the grid (remember to consider the points within the radius)
  2. Loop through each point in the grid
    Loop through each circle and check whether the distance between the circle center and grid point <= radius.
    Calculate the distance using the euclidean distance algorithm.

n = number of circles, m = number of points on the grid
Time Complexity: O(nm)
Space Complexity: O(1)

var countLatticePoints = function(circles) {
  let points = 0;
  let maxX = 0, maxY = 0;
  for (let [x, y, r] of circles) {
    maxX = Math.max(maxX, x + r); // x + r: consider points within the radius
    maxY = Math.max(maxY, y + r); // x + y: consider points within the radius
  }

  for (let i = 0; i <= maxX; i++) {
    for (let j = 0; j <= maxY; j++) {
      for (let [x, y, r] of circles) {
        if (getDist([i, j], [x, y]) <= r) {
          points++;
          break;
        }
      }
    }
  }
  return points;
};

function getDist(p1, p2) {
  let [x1, y1] = p1, [x2, y2] = p2;
  let calc1 = (x2 - x1) * (x2 - x1), calc2 = (y2 - y1) * (y2 - y1);
  return Math.sqrt(calc1 + calc2);
}

javascript

Comments

Popular posts from this blog

Minimum Number of Operations to Sort a Binary Tree by Level - BFS & Cycle Counting Explained [JS]

Beautiful Towers II - Monotonic Increasing Stack [JS]

Reschedule Meetings for Maximum Free Time I - Sliding Window - Constant Space [JS]

Maximum Sum of Distinct Subarrays With Length K - Sliding Window w/ Two Pointers & Set [JS]

Sum of Prefix Scores of Strings - Trie [JS]