zoukankan      html  css  js  c++  java
  • DFS-深度优先算法解决迷宫问题

    /*
    main.cpp
    */
    #define
    _CRT_SECURE_NO_WARNINGS #include<iostream> using namespace std; int sr, sc, dr, dc; int R,C,minLen = 100; char grid[10][10]; bool found[10][10]; void dfs(int r, int c, int len); int main() { freopen("./data.in", "r", stdin); cin >> R >> C; for (int i = 0; i < R;i++) for (int j = 0; j < C; j++) { cin >> grid[i][j]; if (grid[i][j] == 'S'){ sr = i; sc = j; } if (grid[i][j] == 'D'){ dr = i; dc = j; } found[i][j] = false; } dfs(sr, sc, 0); cout << minLen << endl; return 0; } int d[4][2] = { { -1, 0 }, { 1, 0 }, { 0, -1 }, { 0, 1 } }; void dfs(int r, int c, int len) { if (r == dr&&c == dc) { if (minLen > len) minLen = len; return; } for (int i = 0; i < 4; i++) { int nextR = r + d[i][0]; int nextC = c + d[i][1]; if (nextR < 0 || nextR >= R || nextC < 0 || nextC >= C) continue; if (grid[nextR][nextC] == 'X') continue; if (found[nextR][nextC] == true) continue; found[nextR][nextC] = true; dfs(nextR, nextC, len + 1); found[nextR][nextC] = false; } }
    6 6
    S.XD..
    ..XXX.
    ...X..
    ......

    data.in文件

  • 相关阅读:
    工作中Linux常用命令
    自动化测试
    Firefox/Chrome WebDriver浏览器驱动
    Appium
    Python+selenium进行浏览器的连接ChromeOptions
    文件及异常捕获处理
    面向对象练习题
    python函数&面向对象
    python基础
    python8道练习题
  • 原文地址:https://www.cnblogs.com/xin1998/p/7889491.html
Copyright © 2011-2022 走看看