商人渡河问题

/* coder: ACboy date: 2010-3-1 desciption: businessmen river crossing. */ #include using namespace std; int MAXX; int MAXY; // 标记每个状态是否被经过 int vis[4][4][3]; // dx和dy数组用来存储所有的可能的载人方案 // dx数组表示一次船上载几个商人,dy数组表示 // 一次船上载几个随从 int dx[] = {0, 1, 1, 2, 0}; int dy[] = {1, 0, 1, 0, 2}; // 用于保存每一步的结果 int result[20][2]; // 用来记录所有的解决法案的个数 int count; // 检查每一次船的载人方案是否可行 bool CanNext(int x, int y) { if (x >= 0 && x <= 3 && y >= 0 && y <= 3) { if (x == 0 || x == 3) return true; else return x == y; } else { return false; } } // 深度优先遍历(回溯)type用来标记船是离开(1)还是回来(2) void dfs(int x, int y, int type, int pos) { int i; if (x == y && x == 0) { for (i = 0; i < pos - 1; i++) { cout << result[i][0] << "," << result[i][1] << "->"; } cout << result[i][0] << "," << result[i][1] << endl; count++; } else { for (i = 0; i < 5; i++) { if (type == 1) { int newx = x - dx[i]; int newy = y - dy[i]; // 该状态没有被标记过,且船的载人方案可行 if (!vis[newx][newy][type] && CanNext(newx, newy)) { // 标记该状态 vis[newx][newy][type] = 1; // 记录结果 result[pos][0] = newx; result[pos][1] = newy; dfs(newx, newy, 2, pos + 1); // 取消标记 vis[newx][newy][type] = 0; } } else { int newx = x + dx[i]; int newy = y + dy[i]; if (!vis[newx][newy][type] && CanNext(newx, newy)) { vis[newx][newy][type] = 1; result[pos][0] = newx; result[pos][1] = newy; dfs(newx, newy, 1, pos + 1); vis[newx][newy][type] = 0; } } } } } int main() { MAXX = MAXY = 3; count = 0; memset(vis, 0, sizeof(vis)); vis[3][3][2] = 1; result[0][0] = result[0][1] = 3; cout << "可行方案如下:" << endl; dfs(3, 3, 1, 1); cout << "总的可行方案数:" << count << endl; return 0; }

你可能感兴趣的:(其他)