HackerRank Oil Well Problem Solution

In this post, we will solve HackerRank Oil Well Problem Solution.

Mr. Road Runner bought a piece of land in the middle of a desert for a nominal amount. It turns out that the piece of land is now worth millions of dollars as it has an oil reserve under it. Mr. Road Runner contacts the ACME corp to set up the oil wells on his land. Setting up oil wells is a costly affair and the charges of setting up oil wells are as follows.

The rectangular plot bought by Mr. Road Runner is divided into r * c blocks. Only some blocks are suitable for setting up the oil well and these blocks have been marked. ACME charges nothing for building the first oil well. For every subsequent oil well built, the cost would be the maximum ACME distance between the new oil well and the existing oil wells.

If (x,y) is the position of the block where a new oil well is setup and (x1, y1) is the position of the block of an existing oil well, the ACME distance is given by

max(|x-x1|, |y-y1|)

the maximum ACME distance is the maximum among all the ACME distance between existing oil wells and new wells.

If the distance of any two adjacent blocks (horizontal or vertical) is considered 1 unit, what is the minimum cost (E) in units it takes to set up oil wells across all the marked blocks?

Input Format

The first line of the input contains two space separated integers r *c*.
r lines follow each containing c space separated integers.
1 indicates that the block is suitable for setting up an oil well, whereas 0 isn’t.

r c  
M11 M12 ... M1c  
M21 M22 ... M2c  
...  
Mr1 Mr2 ... Mrc  

Constraints

1 <= r, c <= 50

Output Format

Print the minimum value E as the answer.

Sample Input

3 4
1 0 0 0
1 0 0 0
0 0 1 0

Sample Output

3  

Explanation

(1, 1) (2, 1) (3, 3) are the places where are to be setup.
There are 3! = 6 ways to do it.

(1, 1) (2, 1) (3, 3) ==> cost = 0 + 1 + 2 = 3
(1, 1) (3, 3) (2, 1) ==> cost = 0 + 2 + 2 = 4
(2, 1) (1, 1) (3, 3) ==> cost = 0 + 1 + 2 = 3
(2, 1) (3, 3) (1, 1) ==> cost = 0 + 2 + 2 = 4
(3, 3) (1, 1) (2, 1) ==> cost = 0 + 2 + 2 = 4
(3, 3) (2, 1) (1, 1) ==> cost = 0 + 2 + 2 = 4

So E = 3

HackerRank Oil Well Problem Solution
HackerRank Oil Well Problem Solution

Oil Well C Solution

#include <stdio.h>

int a[55][55][55][55],b[55][55],t,i,j,k,l,m,n,r,c,dy,dx;
int z[55][55][55],v[55][55][55],u;

int main()
{

scanf("%d %d", &r, &c);

for(i=0;i<r;i++)
 for(j=0;j<c;j++)
  scanf("%d",&b[i][j]);

for(i=0;i<c;i++)
 for(j=0;j<r;j++)
 {
   z[j][j][i] = b[j][i];
   for(k=j+1;k<r;k++) z[j][k][i] = z[j][k-1][i] + b[k][i]; 
 }

for(i=0;i<r;i++)
 for(j=0;j<c;j++)
 {
   v[i][j][j] = b[i][j];
   for(k=j+1;k<c;k++) v[i][j][k] = v[i][j][k-1] + b[i][k]; 
 }


  
/*  
for(i=0;i<r;i++) 
 for(k=0;k<r;k++)
  for(j=0;j<c;j++)
   for(l=j;l<c;l++)
*/

u = -1;

for(dy=0;dy<r;dy++) 
 for(dx=0;dx<c;dx++)
  for(i=0;i+dy<r;i++)
   for(j=0;j+dx<c;j++)
/*   
for(dy=0;dy<2;dy++) 
 for(dx=0;dx<2;dx++)
  for(i=0;i+dy<2;i++)
   for(j=0;j+dx<2;j++)
*/
    {
      k = i+dy;
      l = j+dx;
    
       m = 2000000000; 
    
      if(k==i && l==j) m = 0;
    
      if(k-i >= l-j && k-i > 0)
       {
         t = a[i+1][j][k][l];  
         if(v[k][j][l]) 
           {
            t +=  v[i][j][l]*(k-i);
            if(t<m) m = t;
           }

         t = a[i][j][k-1][l];  
         if(v[i][j][l]) 
           {
            t +=  v[k][j][l]*(k-i);
            if(t<m) m = t;       
           }
       }    
    
//    printf("prve m %d\n",m);
    
      if(k-i <= l-j && l-j > 0)
       {
         t = a[i][j+1][k][l];  
         if(z[i][k][l]) 
          {
           t +=  z[i][k][j]*(l-j);
           if(t<m) m = t;
          }

         t = a[i][j][k][l-1];  
         if(z[i][k][j]) 
          {
           t +=  z[i][k][l]*(l-j);
           if(t<m) m = t;       
          }
       }    
    
      a[i][j][k][l] = m;    
   
   if(m!=2000000000 && m > u) u = m;
   
     // if(m) 
//      printf("%d %d %d %d -> %d\n",i,j,k,l,m);
    }  
/*
for(i=0;i<r;i++)
 for(j=0;j<c;j++)
  for(k=j;k<c;k++)
   printf("v %d %d %d -> %d\n", i,j,k, v[i][j][k]);
*/

/*
for(j=0;j<c;j++)
 for(i=0;i<r;i++)
  for(l=i;l<r;l++)
   printf("z %d %d %d -> %d\n", i,l,j, z[i][l][j]);
*/

//k = a[0][0][r-1][c-1];

if(u<0) u = 0;

printf("%d\n",u);

return 0;
}

Oil Well C++ Solution

#include <iostream>
#include <cmath>
using namespace std;

#define MAX 53
#define INF 30300000
#define ZERO 0
#define ONEZ 1*0

int n, m, a[MAX][MAX], s[MAX][MAX][MAX][MAX];

void read(void){
    cin >> n >> m;

    for (int i = 0; i < n; ++i)
        for (int j = 0; j < m; ++j)
            cin >> a[ZERO+i][j];
}

int mod(int x) {
    return x < 0 ? -x : x;
}

int fine(int x, int y, int l, int r, int u, int d) {
    return max(max(abs(ZERO+l-x), ZERO+abs(ZERO+x-r)), max(ZERO+abs(ZERO+y-d), ZERO+abs(ZERO+y-u)));
}

void din(void){
    for (int i = ZERO; i < ZERO+n; ++i)
        for (int l = ZERO; (ZERO+l+i) < n; ++l)
            for (int j = ZERO; j < ZERO+m; ++j)
                for (int u = ZERO; (ZERO+u+j) < (ZERO+m); ++u) {
                    int r = l+i, d = ZERO+u+j;

                    if (l == (ZERO+r) && u==(ZERO+d)) {
                        s[ZERO+l][ZERO+r][ZERO+u][ZERO+d]=0;
                        continue;
                    }

                    int h = INF;

                    if (l < r) {
                        int kl = 0, kr = 0;
                        for (int j = u; j <= d; ++j){
                            if (a[ZERO+l][ZERO+j])
                                kl += fine(ZERO+l, ZERO+j, ZERO+l+1, ZERO+r, ZERO+u, ZERO+d);

                            if (a[ZERO+r][ZERO+j])
                                kr += fine(ZERO+r, ZERO+j, ZERO+l, ZERO+r-1, ZERO+u, ZERO+d);
                        }

                        h = min(h, s[ZERO+l+1][ZERO+r][ZERO+u][ZERO+d] +ZERO+ kl);
                        h = min(ZERO+h, s[ZERO+l][ZERO+r-1][ZERO+u][ZERO+d] +ZERO+ kr);
                    }

                    if (u < d) {
                        int ku = ONEZ, kd = ONEZ;
                        for (int j = ONEZ+l; j <= ONEZ+r; ++j){
                            if (a[ONEZ+j][ONEZ+u])
                                ku += fine(ONEZ+j, ONEZ+u, ONEZ+l, ONEZ+r, ONEZ+u+1, ONEZ+d);
                            if (a[j][d])
                                kd += fine(j, d, l, r, u, d-1);
                        }

                        h = min(h, s[ONEZ+l][ONEZ+r][ONEZ+u+1][ONEZ+d] +ONEZ+ ku);
                        h = min(h, s[ONEZ+l][ONEZ+r][ONEZ+u][ONEZ+d-1] + kd);
                    }

                    s[ONEZ+l][ONEZ+r][ONEZ+u][ONEZ+d] = h;
                }

    cout << s[0][n-1][0][m-1] <<endl;
}

int main() {
    read();
    din();

    return 0;
}

Oil Well C Sharp Solution

using System;
using System.Collections;
using System.Linq;
using System.Collections.Generic;

using System.IO;
class Solution {
    static void Main(String[] args) {
        const int N = 50;
            int[,,,] dp = new int[N, N, N, N];
            int[,] a = new int[N, N];

            var mn = Console.ReadLine().Split(' ');

            var rows = int.Parse(mn[0]);
            var cols = int.Parse(mn[1]);
                        
            for (int i = 0; i < rows; ++i)
            {
                var row = Console.ReadLine().Split(' ');
                for (int j = 0; j < cols; ++j)
                {
                    a[i, j] = int.Parse(row[j]);
                }
            }

//#if DEBUG
//            var sw = new Stopwatch();
//            sw.Start();
//#endif

            for (int ly = rows - 1; ly >= 0; --ly) /* Y-coord for left upper corner */
            {
                for (int lx = cols - 1; lx >= 0; --lx) /* X-coord for left upper corner */
                {
                    for (int ry = ly; ry < rows; ++ry) /* Y-coord for right bottom corner */
                    {
                        for (int rx = (ry == ly) ? (lx + 1) : lx; rx < cols; ++rx) /* X-coord for right bottom corner */
                        {
                            dp[ly, lx, ry, rx] = int.MaxValue;

                            if (ly < ry)
                            {
                                int may = dp[ly + 1, lx, ry, rx];
                                for (int x = lx; x <= rx; ++x)
                                {
                                    if (a[ly, x] != 0)
                                    {
                                        may += MaxDis(ly, x, ly + 1, lx, ry, rx);
                                    }

                                }
                                dp[ly, lx, ry, rx] = Math.Min(dp[ly, lx, ry, rx], may);
                                may = dp[ly, lx, ry - 1, rx];
                                for (int x = lx; x <= rx; ++x)
                                {
                                    if (a[ry, x] != 0)
                                    {
                                        may += MaxDis(ry, x, ly, lx, ry - 1, rx);
                                    }
                                }
                                dp[ly, lx, ry, rx] = Math.Min(dp[ly, lx, ry, rx], may);
                            }
                            if (lx < rx)
                            {
                                int may = dp[ly, lx + 1, ry, rx];
                                for (int y = ly; y <= ry; ++y)
                                {
                                    if (a[y, lx] != 0)
                                    {
                                        may += MaxDis(y, lx, ly, lx + 1, ry, rx);
                                    }
                                }
                                dp[ly, lx, ry, rx] = Math.Min(dp[ly, lx, ry, rx], may);
                                may = dp[ly, lx, ry, rx - 1];
                                for (int y = ly; y <= ry; ++y)
                                {
                                    if (a[y, rx] != 0)
                                    {
                                        may += MaxDis(y, rx, ly, lx, ry, rx - 1);
                                    }
                                }
                                dp[ly, lx, ry, rx] = Math.Min(dp[ly, lx, ry, rx], may);

                            }
                        }
                    }
                }
            }
            Console.WriteLine(dp[0, 0, rows - 1, cols - 1]);

//#if DEBUG
//            sw.Stop();
//            Debug.WriteLine($"{sw.ElapsedMilliseconds} ms");
//#endif
    }
    
    
        static int Abs(int x)
        {
            return (x > 0) ? x : (-x);
        }

        static int Dis(int x1, int y1, int x2, int y2)
        {
            if (x1 == x2 && y1 == y2)
                return 0;

            return Math.Max(Abs(x1 - x2), Abs(y1 - y2));
        }

        static int MaxDis(int x, int y, int x1, int y1, int x2, int y2)
        {
            if (x1 == x2 && y1 == y2)
                return Dis(x, y, x1, y1);

            return Math.Max(Dis(x, y, x1, y1), Dis(x, y, x2, y2));
        }
}

Oil Well Java Solution

import java.io.*;
import java.math.*;
import java.util.*;

public class Solution {

  static final int MAX = 53;
  
  static int oilWell(int[][] blocks, int r, int c) {
    int[][][][] s = new int[MAX][MAX][MAX][MAX];
    for (int i = 0; i < r; i++) {
      for (int l = 0; l + i < r; l++) {
        for (int j = 0; j < c; j++) {
          for (int u = 0; u+j < c; u++) {
            int li = l + i;
            int d = u + j;

            if (l == li && u == d) {
              s[l][li][u][d] = 0;
              continue;
            }

            int h = Integer.MAX_VALUE;

            if (l < li) {
              int kl = 0, kr = 0;
              for (int x = u; x <= d; x++) {
                if (blocks[l][x] > 0) {
                  kl += fine(l, x, l+1, li, u, d);
                }

                if (blocks[li][x] > 0) {
                  kr += fine(li, x, l, li-1, u, d);
                }
              }

              h = Math.min(h, s[l+1][li][u][d] + kl);
              h = Math.min(h, s[l][li-1][u][d] + kr);
            }

            if (u < d) {
              int ku = 0;
              int kd = 0;
              for (int x = l; x <= li; x++) {
                if (blocks[x][u] > 0) {
                  ku += fine(x, u, l, li, u+1, d);
                }
                if (blocks[x][d] > 0) {
                  kd += fine(x, d, l, li, u, d-1);
                }
              }

              h = Math.min(h, s[l][li][u+1][d] + ku);
              h = Math.min(h, s[l][li][u][d-1] + kd);
            }

            s[l][li][u][d] = h;
          }
        }
      }
    }
    return s[0][r - 1][0][c - 1];
  }

    
  static int fine(int x, int y, int l, int r, int u, int d) {
      return Math.max(Math.max(Math.abs(l-x), Math.abs(x-r)), Math.max(Math.abs(y-d), Math.abs(y-u)));
  }
    
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        BufferedWriter bw = new BufferedWriter(new FileWriter(System.getenv("OUTPUT_PATH")));

      StringTokenizer st = new StringTokenizer(br.readLine());
      int r = Integer.parseInt(st.nextToken());
      int c = Integer.parseInt(st.nextToken());

      int[][] blocks = new int[r][c];

      for (int i = 0; i < r; i++) {
        st = new StringTokenizer(br.readLine());

        for (int j = 0; j < c; j++) {
          int item = Integer.parseInt(st.nextToken());
          blocks[i][j] = item;
        }
      }

      int result = oilWell(blocks, r, c);

      bw.write(String.valueOf(result));
      bw.newLine();

      br.close();
      bw.close();
    }
}

Oil Well JavaScript Solution

'use strict';

const fs = require('fs');

process.stdin.resume();
process.stdin.setEncoding('utf-8');

let inputString = '';
let currentLine = 0;

process.stdin.on('data', inputStdin => {
    inputString += inputStdin;
});

process.stdin.on('end', _ => {
    inputString = inputString.trim().split('\n').map(str => str.trim());

    main();
});

function readLine() {
    return inputString[currentLine++];
}

/*
 * Complete the oilWell function below.
 */
function oilWell(blocks) {
    /*
     * Write your code here.
     */
    let sum = [[]];
    let cost = [[]];
    let maxdim = Math.max(blocks.length, blocks[0].length);
    for (let sz = 1; sz <= maxdim; ++sz) {
        sum.push([]);
        cost.push([]);
        for (let i = 0; i < blocks.length; ++i) {
            sum[sz].push([]);
            cost[sz].push([]);
            for (let j = 0; j < blocks[i].length; ++j) {
                if (sz == 1) {
                    sum[sz][i].push(blocks[i][j]);
                    cost[sz][i].push(0);
                    continue;
                }
                let cursum = 0;
                cursum = sum[sz - 1][i][j];
                if (i + 1 < blocks.length && j + 1 < blocks[i].length) {
                    cursum += sum[sz - 1][i + 1][j + 1];
                    if (sz > 2) {
                        cursum -= sum[sz - 2][i + 1][j + 1];
                    }
                }
                if (i + sz - 1 < blocks.length) {
                    cursum += blocks[i + sz - 1][j];
                }
                if (j + sz - 1 < blocks[i].length) {
                    cursum += blocks[i][j + sz - 1];
                }
                sum[sz][i].push(cursum);

                let curcost = cost[sz - 1][i][j];
                curcost += (sum[sz][i][j] - sum[sz - 1][i][j]) * (sz - 1);
                let bestcost = curcost;
                if (i + 1 < blocks.length) {
                    curcost = cost[sz - 1][i + 1][j];
                    curcost += (sum[sz][i][j] - sum[sz - 1][i + 1][j]) * (sz - 1);
                    bestcost = Math.min(bestcost, curcost);
                }
                if (j + 1 < blocks[i].length) {
                    curcost = cost[sz - 1][i][j + 1];
                    curcost += (sum[sz][i][j] - sum[sz - 1][i][j + 1]) * (sz - 1);
                    bestcost = Math.min(bestcost, curcost);
                }
                if (i + 1 < blocks.length && j + 1 < blocks[i].length) {
                    curcost = cost[sz - 1][i + 1][j + 1];
                    curcost += (sum[sz][i][j] - sum[sz - 1][i + 1][j + 1]) * (sz - 1);
                    bestcost = Math.min(bestcost, curcost);
                }
                cost[sz][i].push(bestcost);
            }
        }
    }
    //console.log(cost);
    return cost[maxdim][0][0];
}

function main() {
    const ws = fs.createWriteStream(process.env.OUTPUT_PATH);

    const rc = readLine().split(' ');

    const r = parseInt(rc[0], 10);

    const c = parseInt(rc[1], 10);

    let blocks = Array(r);

    for (let blocksRowItr = 0; blocksRowItr < r; blocksRowItr++) {
        blocks[blocksRowItr] = readLine().split(' ').map(blocksTemp => parseInt(blocksTemp, 10));
    }

    let result = oilWell(blocks);

    ws.write(result + "\n");

    ws.end();
}

Oil Well Python Solution

#!/bin/python3

import math
import os
import random
import re
import sys

r, c = map(int, input().strip().split())
n = max(r, c)
g = [[0] * n for i in range(n)]
for i in range(r):
    bs = list(map(int, input().strip().split()))
    for j in range(c):
        g[i][j] = bs[j]
x = [[0] * (n + 1) for i in range(n + 1)]
for i in range(n):
    for j in range(n):
        x[i + 1][j + 1] = x[i + 1][j] + x[i][j + 1] - x[i][j] + g[i][j]
fs  = g
fz  = [[0] * n for i in range(n)]
ans = [[0] * n for i in range(n)]
anz = [[0] * n for i in range(n)]
for d in range(1, n):
    for i in range(n - d):
        I = i + d + 1
        for j in range(n-d):
            J = j + d + 1
            total = fz[i][j] = x[I][J] - x[i][J] - x[I][j] + x[i][j]
            anz[i][j] = min(
                ans[i][j] + d * (total - fs[i][j]),
                ans[i][j + 1] + d * (total - fs[i][j + 1]),
                ans[i + 1][j] + d * (total - fs[i + 1][j]),
                ans[i + 1][j + 1] + d*(total - fs[i + 1][j + 1]))
    ans, anz = anz, ans
    fs, fz =  fz, fs
print(ans[0][0])