Walking on the Safe Side |
Suppose you want to go from the park to the railway station, and do not want to walk more than the required number of blocks. You also want to make your way avoiding the underground passages, that would introduce extra delay. Your task is to determine the number of different paths that you can follow from the park to the station, satisfying both requirements.
The example in the picture illustrates a city with 4 E-W streets and 5 N-S streets. Three intersections are marked as unsafe. The path from the park to the station is 3 + 4 = 7 blocks long and there are 4 such paths that avoid the underground passages.
The first line of the input contains the number of East-West streets W and the number of North-South streets N. Each one of the following W lines starts with the number of an East-West street, followed by zero or more numbers of the North-South crossings which are unsafe. Streets are numbered from 1.
The number of different minimal paths from the park to the station avoiding underground passages.
1 4 5 1 2 2 3 3 5 4
4
题意:一个人要从左上角走到右下角。中间有些点是不能走的,要求出最小步数的路径有多少条。
思路:记忆化搜索,注意输入格式,还有方向只能向下和向右。
#include <stdio.h> #include <string.h> #include <ctype.h> #include <limits.h> const int MAXN = 105, d[2][2] = {{1, 0}, {0, 1}}; int t, n, m, map[MAXN][MAXN], dp[MAXN][MAXN], i, j, ans, Min; void dfs(int bu, int x, int y) { int i; if (x == n && y == m) { if (Min > bu) { Min = bu; ans = 0; } ans ++; return; } for (i = 0; i < 2; i ++) { if ((x + d[i][0] >= 1) && (x + d[i][0] <= n) && (y + d[i][1] >= 1) && (y + d[i][1] <= m) && !map[x + d[i][0]][y + d[i][1]] && dp[x + d[i][0]][y + d[i][1]] >= bu + 1) { dp[x + d[i][0]][y + d[i][1]] = bu + 1; dfs(bu + 1, x + d[i][0], y + d[i][1]); } } } int main() { scanf("%d", &t); while (t --) { ans = 0; Min = INT_MAX; memset(map, 0, sizeof(map)); memset(dp, 0, sizeof(dp)); scanf("%d%d%", &n, &m); char c[105]; for (i = 1; i <= n; i ++) { for (j = 1; j <= m; j ++) dp[i][j] = INT_MAX; int sb; scanf("%d", &sb); gets(c); int lenc = strlen(c); c[lenc] = ' '; int num = 0; for (j = 0; j <= lenc; j ++) { if (isdigit(c[j])) { num = num * 10 + c[j] - '0'; } else { map[sb][num] = 1; num = 0; } } } dp[1][1] = 0; dfs(0, 1, 1); printf("%d\n", ans); if (t) printf("\n"); } return 0; }