הערה (קובץ קוד)
קובץ זה הוא קובץ קוד מסוג C.
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#define N 5
#define DONT_KNOW "I_dont_know"
void printIDontKnow()
{
printf("%s", DONT_KNOW);
exit(0);
}
int examB_q4(char mat[N][N]);
int main(void)
{
// uncomment next line if you don't know the answer
// printIDontKnow();
char mat[N][N];
for (int i = 0; i < N; ++i)
{
for (int j = 0; j < N; ++j)
{
if (scanf(" %c", &mat[i][j]) != 1)
{
return 1;
}
}
}
printf("%d", examB_q4(mat));
return 0;
}
//This is a helper function made for you.
//You are not obligated to use it, and are allowed to change it.
//This function receives the current coordinates of the car,
//and returns the new coordinate after moving one step in the given direction.
void get_next_location(int i, int j, int *next_i, int *next_j, char direction)
{
switch (direction)
{
case 'R':
*next_i = i;
*next_j = j + 1;
break;
case 'L':
*next_i = i;
*next_j = j - 1;
break;
case 'U':
*next_i = i - 1;
*next_j = j;
break;
case 'D':
*next_i = i + 1;
*next_j = j;
break;
}
}
// returns the minimum value, but if -1 is one of the values,
// it returns the other one
int exclusiveMin(int a, int b)
{
if (a < b)
{
if (a == -1)
{
return b;
}
return a;
}
if (b == -1)
{
return a;
}
return b;
}
int findTheCar(char map[N][N], int i, int j, char direction, int numOfChanges)
{
if ((i == (N - 1)) && (j == (N - 1)))
{
return numOfChanges;
}
if (i >= N || j >= N || i < 0 || j < 0 || map[i][j] == '-')
{
return -1;
}
int numberOfChanges = -1;
int nextI = i, nextJ = j;
char val = map[i][j];
map[i][j] = '-';
if (val == 'E')
{
get_next_location(i, j, &nextI, &nextJ, direction);
numberOfChanges = findTheCar(
map, nextI, nextJ, direction, numOfChanges
);
}
else
{
// check base case:
get_next_location(i, j, &nextI, &nextJ, val);
numberOfChanges = findTheCar(map, nextI, nextJ, val, numOfChanges);
// change to right
if (val != 'R')
{
get_next_location(i, j, &nextI, &nextJ, 'R');
numberOfChanges = exclusiveMin(
numberOfChanges, findTheCar(
map, nextI, nextJ, 'R', numOfChanges + 1
)
);
}
// change to left
if (val != 'L')
{
get_next_location(i, j, &nextI, &nextJ, 'L');
numberOfChanges = exclusiveMin(
numberOfChanges, findTheCar(
map, nextI, nextJ, 'L', numOfChanges + 1
)
);
}
// change to up
if (val != 'U')
{
get_next_location(i, j, &nextI, &nextJ, 'U');
numberOfChanges = exclusiveMin(
numberOfChanges, findTheCar(
map, nextI, nextJ, 'U', numOfChanges + 1
)
);
}
// change to down
if (val != 'D')
{
get_next_location(i, j, &nextI, &nextJ, 'D');
numberOfChanges = exclusiveMin(
numberOfChanges, findTheCar(
map, nextI, nextJ, 'D', numOfChanges + 1
)
);
}
}
map[i][j] = val;
return numberOfChanges;
}
// this function checks the factory.
int examB_q4(char mat[N][N])
{
return findTheCar(mat, 0, 0, 'E', 0);
}