Problem: Shortest path in a grid between multiple point with a constraint

Problem description:

enter image description here

I'm trying to solve a problem on the internet and I wasn't able to pass all testcases, well, because my logic is flawed and incorrect. The flaw: I assumed starting to the closest 'F' point will get me to the shortest paths always, at all cases.

Thinks I thought of:

  • Turning this into a graph problem and solve it based on it. > don't think this would work because of the constraint?
  • Try to obtain all possible solution combinations > does not scale, if !8 combination exist.
#include <iostream>
#include <utility> 
#include <string>
#include <vector>
#include <queue>
using namespace std;

#define N 4
#define M 4

int SearchingChallenge(string strArr[], int arrLength) {
  int  n = arrLength, m = n, steps = 0, food = 0;
  // initial position of charlie
  int init_j = 0;
  int init_i = 0;
  queue<pair<int,int>> q;
  // directions
  vector<int> offsets = {0,-1,0,1,0};
  vector<pair<int,int>> food_nodes;
  //store visited nodes, no need for extra work to be done.
  int visited_nodes[4][4] = {{0}};
  
  // get number of food pieces 
  for(int i = 0; i < m; i++){
    for(int j = 0; j < n ; j++){
      if(strArr[i][j] == 'F')
      {
          food++;
      }
      if(strArr[i][j] == 'C')
      {
        strArr[i][j] = 'O';
        food_nodes.push_back({i,j});
      }
    }
  }
  while(food_nodes.size()>0){
      food_nodes.erase(food_nodes.begin());
      int break_flag=0;
      q.push(food_nodes[0]);
  while(!q.empty()){
      int size = q.size();
      while(size-->0){
      pair<int,int> p = q.front();
      q.pop();
      for(int k = 0; k < 4; k++){
      int ii = p.first + offsets[k], jj = p.second + offsets[k+1];
    /*  if(ii == 0 && jj == 3)
        printf("HI"); */
      if(jj >= 0 && jj < 4 && ii < 4 && ii >=0){
          if(strArr[ii][jj] == 'F'){
             strArr[ii][jj] = 'O';
            while(!q.empty())
                q.pop();
            break_flag=1;
            food--;
            food_nodes.push_back({ii,jj});
            break;
          }
          if(strArr[ii][jj] == 'O')
            q.push({ii,jj});
            
            
            if(strArr[ii][jj] == 'H' && food == 0)
                return ++steps;
        }   
     }
    if(break_flag==1)
        break;
    }
    steps++;
    if(break_flag==1)
        break;
  }
}
  return 0;
}

int main(void) { 
   
  // keep this function call here
  /* Note: In C++ you first have to initialize an array and set 
     it equal to the stdin to test your code with arrays. */

  //passing testcase
  //string A[4] = {"OOOO", "OOFF", "OCHO", "OFOO"};
  //failing testcase
  string A[4] = {"FOOF", "OCOO", "OOOH", "FOOO"}
  int arrLength = sizeof(A) / sizeof(*A);
  cout << SearchingChallenge(A, arrLength);
  return 0;
    
}

Your help is appreciated.


I have wrote the javascript solution for the mentioned problem..

function SearchingChallenge(strArr) {

  // create coordinate array 
  const matrix = [
    [0, 0], [0, 1], [0, 2], [0, 3],
    [1, 0], [1, 1], [1, 2], [1, 3],
    [2, 0], [2, 1], [2, 2], [2, 3],
    [3, 0], [3, 1], [3, 2], [3, 3]
  ]
  // flatten the strArr
  const flattenArray = flatten(strArr)
  // segreagate and map flattenArray with matrix to get coordinate of food,charlie and home 
  const segregatedCoordinates = flattenArray.reduce((obj, char, index) => {
    if (char === 'F') obj['food'].push(matrix[index])
    else if (char === 'C') obj['dog'] = matrix[index]
    else if (char === 'H') obj['home'] = matrix[index]
    return obj
  }, { "food": [], dog: null, home: null })

  // construct possible routes by permutating food coordinates
  let possibleRoutes = permuate(segregatedCoordinates['food'])
  // push dog and home in possibleRoutes at start and end positions
  possibleRoutes = possibleRoutes.map((route) => {
    return [segregatedCoordinates['dog'], ...route, segregatedCoordinates['home']]
  })
  // Calculate distances from every possible route 
  const distances = possibleRoutes.reduce((distances, route) => {
    let moveLength = 0
    for (let i = 0; i < route.length - 1; i++) {
      let current = route[i], next = route[i + 1]
      let xCoordinatePath = current[0] > next[0] ? (current[0] - next[0]) : (next[0] - current[0])
      let yCoordinatePath = current[1] > next[1] ? (current[1] - next[1]) : (next[1] - current[1])
      moveLength += xCoordinatePath + yCoordinatePath
    }
    distances.push(moveLength)
    return distances
  }, [])

  return Math.min(...distances);
}

function permuate(arr) {
  if (arr.length <= 2) return (arr.length === 2 ? [arr, [arr[1], arr[0]]] : arr)
  return arr.reduce((res, ele, index) => {
    res = [...res, ...permuate([...arr.slice(0, index), ...arr.slice(index + 1)]).map(val => [ele, ...val])]
    return res
  }, [])
}


function flatten(inputtedArr) {
  return inputtedArr.reduce((arr, row) => {
    arr = [...arr, ...row]
    return arr
  }, [])
}

console.log(SearchingChallenge(['FOOF', 'OCOO', 'OOOH', 'FOOO']));