C#迷宫代码

int Player_x = 0;
int Player_y = 0;
int[,] intArray_2 = new int[20, 20]{
  {0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1},
          {1,0,1,0,1,0,0,0,0,0,1,0,0,0,0,0,1,1,1,1},
          {1,0,0,0,1,1,0,0,1,0,1,0,1,1,0,1,0,0,0,1},
          {1,0,1,0,0,0,0,1,1,0,1,0,1,0,0,1,0,1,0,1},
          {1,0,1,0,1,1,0,0,1,0,0,0,1,0,1,1,0,1,0,1},
          {1,0,1,0,0,0,1,0,1,1,1,1,0,0,1,0,0,1,0,1},
          {1,0,1,0,1,1,0,0,1,0,0,1,0,1,1,0,1,0,0,1},
          {1,0,1,0,1,0,0,1,0,0,1,0,0,1,0,0,1,0,1,1},
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
C# 迷宫求解可以通过深度优先搜索(DFS)或广度优先搜索(BFS)来实现。下面是一个基于DFS算法的C#代码示例,可以帮助你理解迷宫求解的实现过程: ```csharp using System; using System.Collections.Generic; class MazeSolver { private int[,] maze; // 迷宫地图 private bool[,] visited; // 记录是否访问过 private int row, col; // 迷宫的行和列 private int startRow, startCol; // 起点的位置 private int endRow, endCol; // 终点的位置 public MazeSolver(int[,] maze, int startRow, int startCol, int endRow, int endCol) { this.maze = maze; row = maze.GetLength(0); col = maze.GetLength(1); this.startRow = startRow; this.startCol = startCol; this.endRow = endRow; this.endCol = endCol; visited = new bool[row, col]; } public bool Solve() { return DFS(startRow, startCol); } private bool DFS(int r, int c) { if (r == endRow && c == endCol) { return true; // 到达终点,返回true } visited[r, c] = true; // 标记为已访问 // 按顺序尝试向上、右、下、左四个方向走 int[] dr = { -1, 0, 1, 0 }; int[] dc = { 0, 1, 0, -1 }; for (int i = 0; i < 4; i++) { int nr = r + dr[i]; int nc = c + dc[i]; // 检查是否越界,是否可走,是否已访问过 if (nr < 0 || nr >= row || nc < 0 || nc >= col) { continue; } if (maze[nr, nc] == 1 || visited[nr, nc]) { continue; } // 递归尝试下一步 if (DFS(nr, nc)) { return true; // 找到一条可行路径,返回true } } return false; // 四个方向都尝试过了,无解,返回false } } class Program { static void Main(string[] args) { int[,] maze = { { 0, 0, 1, 0, 0 }, { 0, 0, 1, 0, 0 }, { 0, 0, 0, 0, 1 }, { 0, 1, 1, 0, 0 }, { 0, 0, 0, 1, 0 } }; int startRow = 0, startCol = 0; int endRow = 4, endCol = 4; MazeSolver solver = new MazeSolver(maze, startRow, startCol, endRow, endCol); if (solver.Solve()) { Console.WriteLine("迷宫有解!"); } else { Console.WriteLine("迷宫无解!"); } } } ``` 上述代码中,我们使用DFS算法从起点开始搜索,按顺序尝试向上、右、下、左四个方向走,直到到达终点或四个方向都无法继续走。如果找到一条可行路径,返回true;否则返回false。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值