Erect The Fence

Solution For Erect The Fence

Problem Description:

There is a rectangular grid of integers in which some cells are blocked. You are given a list of integers heights where heights[i] represents the height of and opened cell at index i. You are also given integers row and gate where (row, gate) represents that the cell (row, gate) is blocked. Each cell is adjacent to its four adjacent cells(i.e., up, down, left, and right).

You want to build a fence such that it surrounds the rectangular grid and has the following properties:
– The fence should be continuous and have all its corners in the grid.
– The fence should have a minimum height. That is, the height of the fence should be the least among all fences that can be built to surround the grid.
– The fence should not intersect any cell that is not blocked.

Return an integer array answer where answer = [isPossible, height], where isPossible is True if it is possible to build such a fence, and height is the minimum height of the fence. If it is not possible to build a fence according to the above rules, return an empty array.

Example 1:

Input: heights = [1,2,2,1], rows = 1, gate = 3
Output: [true, 1] Explanation: The fence can be built around the shaded area with a minimum height of 1.

Example 2:

Input: heights = [1,2,3,4], rows = 2, gate = 2
Output: [false] Explanation: It is impossible to build a fence around the given grid since it would intersect the first cell.


To solve this problem, we need to find a path that surrounds the blocked cell, and at the same time, this path should have the minimum height. To achieve this, we will use BFS to find the shortest path that encloses the blocked cell.

We will start BFS from all four sides(i.e., top, bottom, left, and right) of the blocked cell one by one and save the path and its minimum height that we find. After finding all four paths, we will choose the one with the minimum height.


  1. First, find the index of the blocked cell using (row, gate)
  2. Initialize an empty queue, visited set, and max-height = 0
  3. For each of the four sides(i.e., top, bottom, left, and right) of the blocked cell:
    • Do BFS starting from the index of the blocked cell in that particular direction
    • While doing BFS, maintain a path and the minimum height of the cells in that path
    • If the path encloses the rectangular grid and it has a minimum height less than max-height:
      • set max-height to the minimum height of this path
      • add the path to a list of valid paths
  4. If no valid paths were found, return empty array
  5. If one or more valid paths were found, choose the one with the minimum height and return [true, min_height]

Complexity Analysis:

  1. Time Complexity: O(NM), where N is the number of rows and M is the number of columns of the rectangular grid.
  2. Space Complexity: O(NM), to store the visited set.

Step by Step Implementation For Erect The Fence

This problem can be solved using a divide and conquer algorithm.

We can first sort the points by their x-coordinates. Then, we can divide the points into two halves and recursively solve the problem for each half.

Finally, we can merge the two solutions together.

The time complexity of this algorithm is O(nlogn), where n is the number of points.
def erect_the_fence(points):

# your code here
 * @param {number[][]} points
 * @return {number}
 // this problem can be solved using the gift wrapping algorithm
 // also known as the jarvis march algorithm
var outerTrees = function(points) {
    // if there are less than 4 points, then they are all on the convex hull
    if (points.length < 4) {
        return points;
    // find the point with the lowest x coordinate
    // if there is a tie, choose the point with the lowest y coordinate
    let lowestPoint = points[0];
    for (let i = 1; i < points.length; i++) {
        if (points[i][0] < lowestPoint[0] || (points[i][0] === lowestPoint[0] && points[i][1] < lowestPoint[1])) {
            lowestPoint = points[i];
    // sort the points by angle in relation to the lowest point
    // points with a smaller angle should come first
    points.sort((a, b) => {
        if (a === lowestPoint) {
            return -1;
        if (b === lowestPoint) {
            return 1;
        let thetaA = Math.atan2(a[1] - lowestPoint[1], a[0] - lowestPoint[0]);
        let thetaB = Math.atan2(b[1] - lowestPoint[1], b[0] - lowestPoint[0]);
        return thetaA - thetaB;
    // use the gift wrapping algorithm to find the convex hull
    // start by adding the lowest point to the convex hull
    // then, keep track of the last point added to the convex hull
    // as well as the current point being considered
    // at each step, calculate the angle between the last point added,
    // the current point, and the next point
    // if the angle is less than 0, that means the next point is not
    // part of the convex hull, so move on to the next point
    // otherwise, add the current point to the convex hull and update
    // the last point added
    let convexHull = [lowestPoint];
    let lastPointAdded = lowestPoint;
    let currentPoint = points[0];
    let nextPoint = points[1];
    while (nextPoint !== lowestPoint) {
        let angle = calculateAngle(lastPointAdded, currentPoint, nextPoint);
        if (angle >= 0) {
            lastPointAdded = currentPoint;
            currentPoint = nextPoint;
        } else {
            currentPoint = nextPoint;
        nextPoint = points[(points.indexOf(currentPoint) + 1) % points.length];
    return convexHull;

function calculateAngle(p1, p2, p3) {
    let v1 = [p1[0] - p2[0], p1[1] - p2[1]];
    let v2 = [p3[0] - p2[0], p3[1] - p2[1]];
    return v1[0] * v2[1] - v1[1] * v2[0];
There are many ways to solve this problem. One way would be to use a sorting algorithm to sort the points by their x-coordinates. Then, you could iterate through the sorted points and use a line sweep algorithm to find the points that form the convex hull.

Another way to solve this problem would be to use a divide and conquer approach. You could divide the points into two sets, S1 and S2. Then, you could find the convex hulls of S1 and S2 separately. Finally, you could take the union of the two convex hulls to form the convex hull of the entire set of points.
There are many possible solutions to this problem. One approach would be to use a sorting algorithm to sort the points in terms of their x-coordinates. Then, we could use a greedy algorithm to construct the fence. Starting from the leftmost point, we would add points to the fence until we reach a point where the next point to be added would create a fence with a turn greater than 180 degrees. At that point, we would backtrack to the last point added to the fence, and add the point with the next smallest x-coordinate. We would continue this process until we reach the rightmost point.

Another approach would be to use a convex hull algorithm. This would give us the points on the fence with the minimum number of turns.

Scroll to Top
[gravityforms id="5" description="false" titla="false" ajax="true"]