关于走格子的问题

本文深入探讨了迷宫路径寻找的算法,包括深度优先搜索(DFS)和宽度优先搜索(BFS),讲解了如何计算从起点到终点的所有可能路径数量,以及如何找到最短路径。同时,介绍了如何在复杂迷宫中避免障碍物,实现路径寻找,以及判断是否存在唯一路径到达终点。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

dfs: 所有可能的路径,是否存在某一条路径

bfs: 遍历图,最短路径

深度优先搜索利用了栈进行计算,而宽度优先搜索则利用了队列进行计算

1.简单版:从(0,0)走到(n,m),只能往下或往右走,最短的路径。(这里最短路径的意思就是只会走m+n个空格)注意这里的矩阵大小是(m+1)*(n+1)

多少种走法:C(m+n,n),或者用动态规划的方式求解。

记录路径:用dfs

typedef pair<int,int> v;
int m, n;
int cnt = 0;
#define M 100
#define N 100
int dx[2]={1,0};
int dy[2]={0,1};
bool vis[M][N];
void print(vector<v> res){
    for(int i =0 ; i < res.size(); i++){
        cout<<"("<<res[i].first<< ","<< res[i].second<<")";
    }
    cout<<endl;
}
void dfs(vector<v> res, int x, int y){
    if(x <0 || x>= m || y <0 || y >=n) return;
    if(vis[x][y] == true) return;
    if( x == m-1 && y == n-1){
        print(res);
        cnt++;
        return;
    }
   
    vis[x][y] = true;
    res.push_back(v(x,y));
    dfs(res,x+1,y);
    dfs(res,x,y+1);
    vis[x][y] = false;
}
int main(){
    
    cin >> m >> n;
    memset(vis,false,sizeof(vis));
    vector<v> res;
    dfs(res,0,0);
    cout<< "total:"<< cnt<<endl;
}

PS进阶:在如下8*6的矩阵中,请计算从A移动到B一共有多少走法?要求每次只能向上或向右移动一格,并且不能经过P。

首先从A到B总共有c(7+5,5)种走法,从A到P有c(3+3,3)种走法,从P到B有c(4+2,2)种走法。

所以不经过点P得走法共有c(12,5)-(c(6,3)*c(6,2))种,即492种,

2. 走迷宫,可以走两个方向。

3.复杂版走迷宫,中间有些不能走,四个方向都可以走。

参考链接:https://blog.csdn.net/qq_37703898/article/details/78445787

多少种? 动态规划,对于不能走的地方直接置0。

记录所有路径:dfs

输出最短路径的长度

typedef pair<int,int> v;
queue<v> q;
#define N 3
#define M 3
char a[M][N];
int b[M][N];
bool vis[M][N];
int dx[4] = {-1,1,0,0};
int dy[4]= {0,0,1,-1};
int bfs(int m, int n){
    q.push(v(m,n));
    b[m][n] = 0;
    while(!q.empty()){
        v cur = q.front();
        q.pop();
        if(cur.first == M && cur.second == N){
            break;
        }
        for(int i =0 ; i < 4; i++){
            int x = cur.first + dx[i];
            int y = cur.second + dy[i];
            if(x >=0 && x < M && y >=0 && y < N && a[x][y] != '#' && vis[x][y] != true){
                // b[][]记录的是该坐标上的路径长度;如果是记录路径,则存储的是上一个路径坐标。具体见下一段代码
                b[x][y] = b[cur.first][cur.second] +1; 
                q.push(v(x,y));
                vis[x][y]  = true;
            }
        }
    }
    return b[M-1][N-1];
}
int main(){
    for(int i = 0 ; i < N; i++){
        for(int j = 0; j < N; j++){
            cin>> a[i][j];
        }
    }
    cout<< bfs(0,0);
    
}

记录最短路径:

  • 利用bfs走迷宫,创建两个数组vis[][]和b[][],一个记录当前点是否访问过,另一个记录当前访问点的前一个点是哪个;然后回溯最短路径的点。只要搜索一次,第一次搜索到的结果就是最短的
typedef pair<int,int> v;
queue<v> q;
#define N 3
#define M 3
char a[M][N];
v b[M][N];
bool vis[M][N];
int dx[4] = {-1,1,0,0};
int dy[4]= {0,0,1,-1};
void bfs(int m, int n){
    q.push(v(m,n));
    b[m][n] = v(m,n);
    while(!q.empty()){
        v cur = q.front();
        q.pop();
        if(cur.first == M && cur.second == N){
            break;
        }
        for(int i =0 ; i < 4; i++){
            int x = cur.first + dx[i];
            int y = cur.second + dy[i];
            if(x >=0 && x < M && y >=0 && y < N && a[x][y] != '#' && vis[x][y] != true){
                b[x][y] = cur;
                cout<< x<<y<<"("<<cur.first << "," << cur.second << ")"  << endl;
                q.push(v(x,y));
                vis[x][y]  = true;
            }
        }
    }
}
int main(){
    for(int i = 0 ; i < N; i++){
        for(int j = 0; j < N; j++){
            cin>> a[i][j];
        }
    }
    bfs(0,0);
    int x = M-1, y  =N-1;
    stack<v> s;
    while(1){
        s.push(v(x,y));
        if(x == 0 && y == 0) break;
        int mx = b[x][y].first;
        int my = b[x][y].second;
        x = mx;
        y = my;
    }
 
    while(!s.empty()){
        cout<< "("<<s.top().first << "," << s.top().second << ")" ;
        s.pop();
    }
    return 0;
    
}
  • 利用dfs,主要思想是通过回溯搜索出所有的结果,然后比较得到最小的。但是这种方法比较耗时。

4.复杂版 走迷宫,中间有些不能走,四个方向都可以走,求是否存在一条唯一的路径,达到终点。

这个可以利用回溯法,用一个矩阵来记录当前这个点是否可达。

### JavaWeb实现网格布局 在JavaWeb开发中,网格布局可以通过前端框架(如Bootstrap、Tailwind CSS等)或者自定义CSS来实现。如果需要动态生成网格布局,则可以在后台使用Java处理逻辑并将数据传递到前端。 #### 使用Bootstrap实现网格布局 以下是基于Bootstrap的一个简单示例: ```html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/css/bootstrap.min.css" rel="stylesheet"> <title>Grid Layout Example</title> </head> <body> <div class="container"> <h1>Simple Grid Layout</h1> <div class="row"> <div class="col-md-4 border">Column 1</div> <div class="col-md-4 border">Column 2</div> <div class="col-md-4 border">Column 3</div> </div> </div> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/js/bootstrap.bundle.min.js"></script> </body> </html> ``` 此代码展示了如何创建一个三列的响应式网格布局[^1]。 --- ### JavaWeb实现路径规划算法 对于路径规划算法的应用场景,通常涉及到地图导航、物流配送等领域。常见的路径规划算法包括Dijkstra算法、A*算法和Floyd-Warshall算法等。下面是一个简单的A*算法实现,并展示其在JavaWeb中的应用方式。 #### A*算法简介 A*是一种启发式搜索算法,适用于寻找两点之间的最短路径。它结合了实际代价函数g(n)和估计代价函数h(n),其中f(n)=g(n)+h(n)[^3]。 #### A*算法的Java实现 以下是一个简化版本的A*算法实现: ```java import java.util.*; public class AStarAlgorithm { private static final int[][] DIRECTIONS = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}}; public List<int[]> findPath(int startX, int startY, int endX, int endY, boolean[][] grid) { PriorityQueue<Node> openList = new PriorityQueue<>(Comparator.comparingInt(node -> node.f)); Map<String, Node> closedList = new HashMap<>(); openList.add(new Node(startX, startY, null)); while (!openList.isEmpty()) { Node current = openList.poll(); String key = getKey(current.x, current.y); if (closedList.containsKey(key)) continue; closedList.put(key, current); if (current.x == endX && current.y == endY) { return reconstructPath(current); } for (int[] dir : DIRECTIONS) { int newX = current.x + dir[0]; int newY = current.y + dir[1]; if (newX >= 0 && newX < grid.length && newY >= 0 && newY < grid[0].length && !grid[newX][newY]) { openList.add(new Node(newX, newY, current)); } } } return Collections.emptyList(); // No path found. } private String getKey(int x, int y) { return x + "," + y; } private List<int[]> reconstructPath(Node node) { List<int[]> path = new ArrayList<>(); while (node != null) { path.add(0, new int[]{node.x, node.y}); node = node.parent; } return path; } private static class Node { int x, y; int g = Integer.MAX_VALUE; // Cost from start to this node int h; // Heuristic cost estimate from this node to goal int f; // Total cost: f = g + h Node parent; Node(int x, int y, Node parent) { this.x = x; this.y = y; this.parent = parent; this.g = parent == null ? 0 : parent.g + 1; this.h = Math.abs(x - endX) + Math.abs(y - endY); // Manhattan distance heuristic this.f = this.g + this.h; } } } ``` 在此基础上,可以将该算法集成到JavaWeb应用程序中,用于计算特定的地图上的最优路径[^2]。 --- ### 前端与后端交互设计 为了使路径规划算法能够在JavaWeb环境中运行,需考虑前后端分离的设计模式。例如,前端发送请求至后端API接口,提供起点坐标、终点坐标以及障碍物分布信息;后端接收到参数后调用上述算法完成路径计算,并返回结果给前端渲染显示。 #### API接口示例 假设采用Spring Boot作为后端框架,以下是一个RESTful风格的控制器方法: ```java @RestController @RequestMapping("/api/pathfinding") public class PathFindingController { @PostMapping("/astar") public ResponseEntity<List<int[]>> calculatePath(@RequestBody PathRequest request) { AStarAlgorithm aStar = new AStarAlgorithm(); List<int[]> result = aStar.findPath( request.getStartX(), request.getStartY(), request.getEndX(), request.getEndY(), request.getObstacles() ); return ResponseEntity.ok(result); } } class PathRequest { private int startX; private int startY; private int endX; private int endY; private boolean[][] obstacles; // Getters and Setters omitted for brevity } ``` ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值