走迷宫走的最短步数
#include <iostream>
#include <climits>
using namespace std;
char a[105][105];
int f[105][105];
int n, m, r, c;
int dx[4] = { 1 ,0 , -1, 0 };
int dy[4] = { 0 ,-1,0,1 };
void dfs(int x, int y, int tep) {
if (f[x][y] > tep) {
f[x][y] = tep;
for (int i = 0; i < 4; i++) {
int xx = x + dx[i], yy = y + dy[i];
if (a[xx][yy] == '.') {
dfs(xx, yy, tep + 1);
}
}
}
}
int main()
{
cin >> n >> m >> r >> c;
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= m; j++) {
cin >> a[i][j];
f[i][j] = INT_MAX;
}
}
dfs(1, 1, 1);
cout << f[r][c];
return 0;
}
滑行问题
#include <iostream>
#include <climits>
#include <algorithm>
using namespace std;
int a[105][105], f[105][105];
int dx[4] = { 1,-1,0,0 };
int dy[4] = { 0,0,1,-1 };
int n, m, ans = 0;
int dfs(int x, int y) {
if (f[x][y] != 0)
return f[x][y];
int t = 0;
f[x][y] = 1;
for (int i = 0; i < 4; i++) {
int xx = x + dx[i], yy = y + dy[i];
if (xx >= 1 && xx <= n && yy >= 1 && yy <= m && a[xx][yy] < a[x][y]) {
t = dfs(xx, yy) + 1;
}
f[x][y] = max(t, f[x][y]);
}
return f[x][y];
}
int main()
{
cin >> n >> m;
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= m; j++) {
cin >> a[i][j];
}
}
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= m; j++) {
f[i][j] = dfs(i, j);
ans = max(ans, f[i][j]);
}
}
cout << ans;
return 0;
}