解救小哈

Description

详见 啊哈算法 解救小哈章节

标准的dfs求最短路径,dfs其实就是暴力,这道题对我来说有1个难点。第一个是return的用法,return的时候,返回到调用return的那个函数上,然后就会执行book[i]=0,然后就可以在这个点进行其他位置的搜索。思路其实很简单,也是典型的DFS例题

 1 #include<iostream>
 2 using namespace std;
 3 int n, m, mins = 99999;
 4 int w[20][20], book[20][20];
 5 int x1, y1, x2, y2;
 6 int x, y;
 7 int nextX[4] = {1, 0, -1};
 8 int nextY[4] = {1, 0, -1};
 9 void dfs(int a, int b, int step) {
10     int tx, ty;
11     if(a == x2 && b == y2) {
12         //cout << "等于啦";
13         if(step <= mins) {
14             mins = step;
15             //cout << "step" << mins;
16         }
17         return;
18     } else {
19         
20         for(int i = 0; i < 3; i++) {
21             for(int j = 0; j < 3; j++) {
22                 tx = a+nextX[i];
23                 ty = b+nextY[j];
24                 if(tx<1 || tx>m || ty<1 || ty>n) {
25                 } else {
26                     if(w[tx][ty]==0 && book[tx][ty]==0)
27                     {
28                         book[tx][ty] = 1;
29                         dfs(tx, ty, ++step);
30                         book[tx][ty] = 0;
31                     }
32                 }
33             }
34         }
35     }
36 }
37 int main()
38 {
39     cin >> n >> m;
40     for(int i = 1; i <= n; i++) {
41         for(int j = 1; j <= m; j++) {
42             int x;
43             cin >> x;
44             w[i][j] = x;
45         }
46     }
47     cin >> x1 >> y1 >> x2 >> y2;
48     book[x1][y1] = 1;
49     dfs(x1, y1, 0);
50     cout << mins;
51 }
52 /*
53 5 4
54 0 0 1 0
55 0 0 0 0
56 0 0 1 0
57 0 1 0 0 
58 0 0 0 1
59 1 1 4 3
60 */
原文地址:https://www.cnblogs.com/wzy-blogs/p/9158750.html