溫馨提示×

怎樣用c#遞歸解決迷宮問題

c#
小樊
81
2024-10-09 07:00:35
欄目: 編程語言

在C#中,可以使用遞歸回溯算法來解決迷宮問題。以下是一個示例代碼,展示了如何使用遞歸方法解決迷宮問題:

using System;

public class Maze
{
    public int[,] Grid { get; set; }
    public int StartRow { get; set; }
    public int StartCol { get; set; }
    public int EndRow { get; set; }
    public int EndCol { get; set; }

    public Maze(int[,] grid, int startRow, int startCol, int endRow, int endCol)
    {
        Grid = grid;
        StartRow = startRow;
        StartCol = startCol;
        EndRow = endRow;
        EndCol = endCol;
    }

    public bool IsValidMove(int row, int col)
    {
        return row >= 0 && row < Grid.GetLength(0) && col >= 0 && col < Grid.GetLength(1) && Grid[row, col] == 0;
    }

    public bool SolveMaze()
    {
        return RecursiveBacktracking(StartRow, StartCol);
    }

    private bool RecursiveBacktracking(int row, int col)
    {
        if (row == EndRow && col == EndCol)
        {
            return true;
        }

        Grid[row, col] = 1; // Mark the cell as visited

        // Explore all possible directions: up, down, left, right
        bool foundSolution = false;
        if (IsValidMove(row - 1, col))
        {
            foundSolution = foundSolution || RecursiveBacktracking(row - 1, col);
        }
        if (IsValidMove(row + 1, col))
        {
            foundSolution = foundSolution || RecursiveBacktracking(row + 1, col);
        }
        if (IsValidMove(row, col - 1))
        {
            foundSolution = foundSolution || RecursiveBacktracking(row, col - 1);
        }
        if (IsValidMove(row, col + 1))
        {
            foundSolution = foundSolution || RecursiveBacktracking(row, col + 1);
        }

        Grid[row, col] = 0; // Unmark the cell as visited

        return foundSolution;
    }
}

public class Program
{
    public static void Main()
    {
        int[,] grid = new int[,]
        {
            { 0, 1, 0, 0, 0 },
            { 0, 1, 0, 1, 0 },
            { 0, 0, 0, 1, 0 },
            { 1, 1, 1, 1, 0 },
            { 0, 0, 0, 0, 0 }
        };

        Maze maze = new Maze(grid, 0, 0, 4, 4);
        bool solution = maze.SolveMaze();

        if (solution)
        {
            Console.WriteLine("Solution found!");
        }
        else
        {
            Console.WriteLine("No solution found.");
        }
    }
}

在這個示例中,我們定義了一個Maze類,它包含一個二維數(shù)組Grid來表示迷宮,以及起始行、起始列、結(jié)束行和結(jié)束列。IsvalidMove方法用于檢查是否可以在指定的位置移動,SolveMaze方法調(diào)用遞歸回溯算法來解決迷宮問題。

RecursiveBacktracking方法中,我們首先檢查當(dāng)前位置是否是終點。如果是,則返回true。然后,我們將當(dāng)前位置標(biāo)記為已訪問,并嘗試向四個方向(上、下、左、右)遞歸地移動。如果在任何方向上找到解決方案,則返回true。最后,我們將當(dāng)前位置標(biāo)記為未訪問,以便在其他路徑中重新使用。

Main方法中,我們創(chuàng)建了一個迷宮實例,并調(diào)用SolveMaze方法來解決迷宮問題。根據(jù)返回的布爾值,我們可以判斷是否存在解決方案。

0