Improvements

mail@pastecode.io avatar
unknown
csharp
a month ago
2.4 kB
13
Indexable
Never
// Depth-first search loop.
while (this.stack.Size > 0)
{
    location = this.stack.Top();

    // Exit found
    if (this.charMaze[location.Row][location.Column] == 'E')
    {
        exitFound = true;
        break;
    }

    // Path
    this.charMaze[location.Row][location.Column] = '.';

    if (this.charMaze[location.Row + 1][location.Column] == ' ' || this.charMaze[location.Row + 1][location.Column] == 'E')
    {
        // South
        this.stack.Push(new Point(location.Row + 1, location.Column));
    }
    else
    {
        if (this.charMaze[location.Row][location.Column + 1] == ' ' || this.charMaze[location.Row][location.Column + 1] == 'E')
        {
            // East
            this.stack.Push(new Point(location.Row, location.Column + 1));
        }
        else if (this.charMaze[location.Row][location.Column - 1] == ' ' || this.charMaze[location.Row][location.Column - 1] == 'E')
        {
            // West
            this.stack.Push(new Point(location.Row, location.Column - 1));
        }
        else if (this.charMaze[location.Row - 1][location.Column] == ' ' || this.charMaze[location.Row - 1][location.Column] == ' ')
        {
            // North
            this.stack.Push(new Point(location.Row - 1, location.Column));
        }
        else
        {
            // Visited
            this.charMaze[location.Row][location.Column] = 'V';

            // Backtrack
            this.stack.Pop();
        }
    }
}


// Breadth-first search loop.
while (!queue.IsEmpty() && !exitFound)
{
    Point location = this.queue.Dequeue();

    List<Point> directions = new List<Point>()
    {
        new Point(location.Row + 1, location.Column,     location),
        new Point(location.Row,     location.Column + 1, location),
        new Point(location.Row,     location.Column - 1, location),
        new Point(location.Row - 1, location.Column,     location)
    };

    foreach (Point direction in directions)
    {
        if (this.charMaze[direction.Row][direction.Column] == ' ')
        {
            this.queue.Enqueue(direction);
            this.charMaze[direction.Row][direction.Column] = 'V';
        }
        else if (this.charMaze[direction.Row][direction.Column] == 'E')
        {
            this.EndPoint = direction;
            exitFound = true;
            break;
        }
    }
}
Leave a Comment