You are on page 1of 3

using System;

using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CharlieTheDog
{
class Program
{

public class Loc


{
public int x, y;
}

public static Loc searchChar(string [] strArr, char c)


{
Loc loc = new Loc();
int i, j;
for (i = 0; i < 4; i++)
{
for (j = 0; j < 4; j++)
{
if (strArr[i][j] == c)
{
loc.x = i;
loc.y = j;
return loc ;
}
}

}
loc.x = 0;
loc.y = 0;
return loc;
}

public static int count(string [] strArr, char c)


{
int i, j, count = 0;
for (i = 0; i < 4; i++)
{
for (j = 0; j < 4; j++)
{
if (strArr[i][j] == c)
{
count++;
}
}

}
return count;
}

public static int visitIfFeasible(string [] grid, Loc currentLoc, Loc


endLoc, int [,] visited,int remainingFood, int currentSteps)
{
if (currentLoc.x < 0 || currentLoc.x > 3 || currentLoc.y < 0 ||
currentLoc.y > 3)
{
return -1;
}
return visitBoard(grid, currentLoc, endLoc, visited, remainingFood,
currentSteps);
}

public static int visitBoard(string [] grid,Loc currentLoc, Loc endLoc, int


[,] visited,int remainingFood, int currentSteps)
{

if (currentLoc.x == endLoc.x && currentLoc.y == endLoc.y)


{
return (remainingFood == 0 ? currentSteps : -1);
}
if (Convert.ToBoolean(visited[currentLoc.x,currentLoc.y]))
{
return -1;
}

visited[currentLoc.x,currentLoc.y] = 1;
if (grid[currentLoc.x][currentLoc.y] == 'F')
{
remainingFood -= 1;
}
currentSteps += 1;

int currentCost = -1;


Loc loc = new Loc();
loc.x = currentLoc.x + 1;
loc.y = currentLoc.y ;
int subCost = visitIfFeasible(grid, loc, endLoc, visited,
remainingFood, currentSteps);
if (subCost > 0)
{
if (currentCost == -1 || currentCost > subCost)
{
currentCost = subCost;
}
}
loc.x = currentLoc.x - 1;
loc.y = currentLoc.y;
subCost = visitIfFeasible(grid, loc, endLoc, visited, remainingFood,
currentSteps);
if (subCost > 0)
{
if (currentCost == -1 || currentCost > subCost)
{
currentCost = subCost;
}
}
loc.x = currentLoc.x;
loc.y = currentLoc.y-1;
subCost = visitIfFeasible(grid, loc, endLoc, visited, remainingFood,
currentSteps);
if (subCost > 0)
{
if (currentCost == -1 || currentCost > subCost)
{
currentCost = subCost;
}
}
loc.x = currentLoc.x;
loc.y = currentLoc.y+1;
subCost = visitIfFeasible(grid, loc, endLoc, visited, remainingFood,
currentSteps);
if (subCost > 0)
{
if (currentCost == -1 || currentCost > subCost)
{
currentCost = subCost;
}
}

visited[currentLoc.x,currentLoc.y] = 0; // revert

return currentCost;
}

public static void SearchingChallenge(string [] strArr)


{

Loc startLoc = searchChar(strArr, 'C');


Loc endLoc = searchChar(strArr, 'H');
int foodCount = count(strArr, 'F');
int [,] visited = new int[4,4];
int cost = visitBoard(strArr, startLoc, endLoc, visited, foodCount, 0);
Console.WriteLine (cost); // -1 cost means it is not possible.
}

static void Main(string[] args)


{
string[] arr = { "HOOF", "OOOO", "OOOO", "FOOC" };

SearchingChallenge(arr);
}

}
}

You might also like