ד"א תשובות למי שמעוניין:
3: פשוט מאד:
int length(char[] str)
{
if (str == null)
return 0;
else
{
int i=0;
while(str[i] != '\0')
++i;
}
return i;
}
סיבוכיות זמן: כאורך המחרוזת
4. שימו לב שמבקשים רק את החזרת האורך בO)1(
public class MyString
{
int _length;
public MyString(char[] str)
{
_length = length(str) // that we wrote erlier
}
public int Length
{
get
{
return _length;
}
}
}
5. כאן יש 3 דרכים לפיתרון:
א. ללכת לכיוון נקודת הסיום ולסמן משבצות בהם ביקרנו (כלומר, לנסות ללכת שמאלה ולמטה למשל, אם נק' הסיום שמאלית - ומטה, אם נכשלים, חוזרים אחורה והולכים לכיוון ההפוך - אך המימוש של זה לא פשוט.
ב. למדל את הבעיה לגרף, שכל שכן יחובר בקו, ולהריץ על זה מסלולים קצרים למשל, בעזרת BFS או DFS.
ג. הפיתרון המתבקש (עליתי עליו)
מתחילים מנק' ההתחלה ומתחילים לבדוק שכנים (ברקורסיה), אם השכן הוא נק' הסיום, החזר TRUE אחרת, החזר FALSE. כל ריבוע שמבקרים בו - יש לסמן שם VISITED כדי שלא נבקר פעמיים.
בשביל הקוד, השתמשתי בקיר ביטחון (בשביל לפשט את המימוש).
הקוד כתוב בC#:
Matrix class:
public enum eTileType
{
Free,
Wall,
Start,
End
}
public class Tile
{
public bool visited { get; set; }
// lets say, 0=free, 1=wall, 2=start, 3=end
public eTileType type { get; set; }
}
Init matrix + make wall:
static void Main(string[] args)
{
const int size = 6;
Tile[,] mat = new Tile[size + 1, size + 1];
for (int i = 0; i < size + 1; ++i)
for (int j = 0; j < size + 1; ++j)
mat[i, j] = new Tile() { type = eTileType.Free, visited = false };
for (int i = 0; i < size + 1; ++i)
mat[0, i].type = eTileType.Wall;
for (int i = 0; i < size + 1; ++i)
mat[i, size].type = eTileType.Wall;
for (int i = 0; i < size + 1; ++i)
mat[size, size - i].type = eTileType.Wall;
for (int i = 0; i < size + 1; ++i)
mat[size - i, 0].type = eTileType.Wall;
mat[2, 1].type = eTileType.Wall;
mat[2, 2].type = eTileType.Wall;
mat[2, 3].type = eTileType.Wall;
mat[2, 4].type = eTileType.Wall;
mat[2, 6].type = eTileType.Wall;
mat[4, 3].type = eTileType.Wall;
mat[5, 3].type = eTileType.Wall;
mat[1, 2].type = eTileType.Start;
mat[5, 2].type = eTileType.End;
Console.WriteLine("Route was found? " + checkRoute(mat, 1, 2));
}
this is the recursive func:
static bool checkRoute(Tile[,] mat, int i, int j)
{
// If already visited, don't even try it
if (mat[i, j].visited)
return false;
// mark as visited.
mat[i, j].visited = true;
// if its the end, then the route was found
if (mat[i, j].type == eTileType.End)
return true;
// if its a wall, don't continue it.
else if (mat[i, j].type == eTileType.Wall)
return false;
// if any of the neighbours is eventually the end, it will be true.
bool isRoutOk = checkRoute(mat, i - 1, j - 1) ||
checkRoute(mat, i - 1, j) ||
checkRoute(mat, i - 1, j + 1) ||
checkRoute(mat, i, j - 1) ||
checkRoute(mat, i, j + 1) ||
checkRoute(mat, i + 1, j - 1) ||
checkRoute(mat, i + 1, j) ||
checkRoute(mat, i + 1, j + 1);
if (isRoutOk)
Console.WriteLine(string.Format("{0}-{1}", i, j));
return isRoutOk;
}