我比较傻叉,居然忘了用动态规划做,用了递归,各种边界判断,而且数组稍大一点就栈溢出。递归可以剪支,稍微减少一些递归次数。不管怎么样还是贴上自己的傻叉代码吧
#include<iostream> using namespace std; const int M = 10;///列 const int N = 10;///行 int min = N+M; char A[N][M]; ///d=1代表向下走,d=0代表向右走 void f(char A[N][M], int i,int j,int d, int result) { if (i == N-1&&j == M-1) { if (result < min) { min = result; } return; } if (d == 0) ///向右走 { if (j + 1 <= M - 1) ///没走到边界 { if (A[i][j + 1] == ‘b‘) ///下一步是障碍物 { f(A, i, j + 1, 0, result + 1); ///清楚障碍物 if (i + 1 <= N - 1) ///走下面 { if (A[i + 1][j] == ‘0‘) { f(A, i + 1, j, 1, result); } else { f(A, i + 1, j, 1, result + 1); } } } else { f(A, i, j + 1, 0, result); ///向右走 if (i + 1 <= N - 1) ///向下走 { if (A[i + 1][j] == ‘0‘) { f(A, i + 1, j, 1, result + 1); } else { f(A, i + 1, j, 1, result + 2); } } } } else ///已经向右行走到边界 { ///此处i+1<=N-1,否则应该在递归出口 f(A, i + 1, j, 1, result); } } else ////向下行走 { if (i + 1 <= N - 1) ///下边依旧有路 { if (A[i + 1][j] == ‘b‘) { f(A, i + 1, j, 1, result + 1);///向右继续走 if (j + 1 <= M - 1) { if (A[i][j + 1] == ‘0‘) { f(A, i, j + 1, 0, result); } else { f(A, i, j + 1, 0, result + 1); } } } else { if (j + 1 <= M - 1) { if (A[i][j + 1] == ‘0‘) { f(A, i, j + 1, 0, result + 1); } else { f(A, i, j + 1, 0, result + 2); } } f(A, i + 1, j, 1, result); } } else ///已经向下行走到边界 { f(A, i, j + 1, 0, result); } } } /* int main() { for (int i = 0; i < N; i++) { for (int j = 0; j < M; j++) { A[i][j] = ‘0‘; } } A[0][4] = ‘b‘; A[0][5] = ‘b‘; A[2][5] = ‘b‘; A[3][3] = ‘b‘; A[3][4] = ‘b‘; A[3][5] = ‘b‘; A[2][6] = ‘b‘; for (int i = 0; i < N; i++) { for (int j = 0; j < M; j++) { cout << A[i][j] << " "; } cout << endl; } f(A, 0, 0, 0, 0); cout << min << endl; } */
时间: 2024-10-23 16:42:37