DFS-深度优先遍历
2017-02-07 01:18
232 查看
#include <iostream> /* 5 4 0 0 1 0 0 0 0 0 0 0 1 0 0 1 0 0 0 0 0 1 0 0 4 1 Total: 9 7 5 Min: 5 -------------------------------- Process exited with return value 0 Press any key to continue . . . */ using namespace std; int n, m; int minnum = 9999999; int endy1 = 0, endy2 = 0; int maze[20][20] = {0}, book[20][20] = {0}; int direction[4][2] = { {0, 1}, {1, 0}, {0, -1}, {-1, 0} }; void DFS(int x, int y, int step) { if(x == endy1 && y == endy2) { if(step < minnum) { minnum = step; cout << minnum << " "; } return; } for(int i = 0; i <= 3; i++) { int tx = x + direction[i][0]; int ty = y + direction[i][1]; if(tx < 0 || tx > n - 1 || ty < 0 || ty > m - 1) { continue; } if(maze[tx][ty] == 0 && book[tx][ty] == 0) { book[tx][ty] = 1; DFS(tx, ty, step + 1); book[tx][ty] = 0;//尝试结束,取消这个点的标记 } } return; } int main() { cin >> n >> m; for(int i = 0; i < n; i++) { for(int j = 0; j < m; j++) { cin >> maze[i][j]; } } int beginx1, beginx2; cin >> beginx1 >> beginx2 >> endy1 >> endy2; cout << endl << "Total: "; DFS(beginx1, beginx2, 0); cout << endl << "Min: " << minnum; return 0; }
相关文章推荐
- leetcode 653. Two Sum IV - Input is a BST 中序遍历 + 深度优先遍历DFS
- leetcode 671. Second Minimum Node In a Binary Tree 第二小数字 + 深度优先遍历DFS
- leetcode 662. Maximum Width of Binary Tree 二叉树最大宽度 + 深度优先遍历DFS
- DFS 深度优先遍历
- 深度优先遍历 DFS C实现
- 算法基础——DFS(深度优先遍历)
- ZOJ 3861 Valid Pattern Lock(深度优先遍历dfs,有限制条件的全排列)
- 【算法——02】图的遍历——BFS广度优先搜索、DFS深度优先搜索
- leetcode 132. Palindrome Partitioning II 回文子串 + 深度优先遍历DFS(超时) + 动态规划DP + 这道题需要认真学习
- Java 图的建立及DFS深度优先遍历
- 邻接矩阵存储的无向图深度优先(DFS)广度优先(BFS)遍历
- leetcode 650. 2 Keys Keyboard 最小复制粘贴次数 + 深度优先遍历DFS
- leetcode 753. Cracking the Safe 深度优先遍历DFS
- zoj 2100(dfs深度优先遍历)
- 广度优先遍历-BFS、深度优先遍历-DFS
- DFS-深度优先遍历
- python遍历文件夹——深度优先(DFS)/广度优先(BFS)
- 深度优先遍历!!DFS
- leetcode 508. Most Frequent Subtree Sum 子树和 + 一个简单的DFS深度优先遍历的做法
- leetcode 529. Minesweeper 扫雷游戏 + 经典的DFS深度优先遍历