הערה (קובץ קוד)
קובץ זה הוא קובץ קוד מסוג C.
#include <stdio.h>
#include <stdlib.h>
#define M 1000
char getDirection(const char dir, char mat[][M], const int i, const int j)
{
char output = mat[i][j];
if (mat[i][j] == '#')
{
output = dir;
}
mat[i][j] = 'X';
return output;
}
int getIndex(const int index, const char dir, const int maxAtDirection)
{
if (dir == 'D' || dir == 'R')
{
if (index + 1 >= maxAtDirection)
{
return 0;
}
return (index + 1);
}
if (dir == 'U' || dir == 'L')
{
if (index - 1 < 0)
{
return (maxAtDirection - 1);
}
return (index - 1);
}
return index;
}
int getChanged(const char dir)
{
if (dir == 'U' || dir == 'D')
{
return 1;
}
if (dir == 'R' || dir == 'L')
{
return 2;
}
return 0;
}
int breakConditionCheck(char mat[][M], const int i, const int j, int length)
{
if (i == 0 && j == 0)
{
return ++length;
}
if (mat[i][j] == 'X')
{
return -1;
}
return -2;
}
int letPacmanPathRec(
char mat[][M],
const int n, const int m,
int length,
int i, int j, char dir)
{
dir = getDirection(dir, mat, i, j);
if (getChanged(dir) == 1)
{
i = getIndex(i, dir, n);
}
else if (getChanged(dir) == 2)
{
j = getIndex(j, dir, m);
}
const int val = breakConditionCheck(mat, i, j, length);
if (val != -2)
{
return val;
}
return letPacmanPathRec(mat, n, m, ++length, i, j, dir);
}
int lenPacmanPath(char mat[][M], const int n, const int m)
{
return letPacmanPathRec(mat, n, m, 0, 0, 0, '#');
}
// Do not change these functions
void fillMatrix(char mat[][M], const int n, const int m)
{
for (int i = 0; i < n; i++)
{
for (int j = 0; j < m; j++)
{
scanf(" %c", &mat[i][j]);
}
}
}
// Do not change the main function
int main()
{
int n = 0, m = 0;
int student_output = -2;
scanf(" %d %d", &n, &m);
char (*mat)[M] = malloc(n * M * sizeof(char));
if (mat)
{
fillMatrix(mat, n, m);
student_output = lenPacmanPath(mat, n, m);
}
printf("%d", student_output);
free(mat);
return 0;
}