Accept: 177 Submit: 3117
Time Limit: 1000 mSec Memory Limit : 128MB
Problem Description
Input
There will be at most 25 test cases. Each test begins with two integers R and C (2 ≤ R,C ≤ 15, R∗C ≤ 30), the number of rows and columns of the maze. The next R rows represent the maze. Each line contains exactly C characters (without leading or trailing spaces), each of them will be either ‘#’ or one of the nine non-zero digits. There will be at least one non-obstacle squares (i.e. squares with a non-zero digit in it) in the maze. The input is terminated by a test case with R = C = 0, you should not process it.
Output
For each test case, print the biggest number you can find, on a single line.
Sample Input
Sample Output
791452384
题解:一看题目觉得是个大水题,dfs一下就行,然后果断TLE,这个题对效率要求还是比较高的,两个比较重要的剪枝:
1、如果剩余最长可走长度加上目前已有长度小于答案的长度,直接return.
2、如果剩余最长可走长度加上目前已有长度等于答案的长度,比较字典序,如果答案更优就retrun.
#include <bits/stdc++.h> using namespace std; const int maxn = ; int n, m, cnt;
int head, tail;
pair<int,int> que[maxn*maxn];
int dx[] = { ,-,, };
int dy[] = { ,,-, };
char gra[maxn][maxn];
bool vis[maxn][maxn],vvis[maxn][maxn];
string ans, tmp; int h(int x,int y) {
head = tail = ;
int cnt = ;
que[tail++] = make_pair(x, y);
memcpy(vvis, vis, sizeof(vis)); while (head < tail) {
pair<int, int> temp = que[head++];
for (int i = ; i < ; i++) {
int xx = temp.first + dx[i], yy = temp.second + dy[i];
if ( <= xx && <= yy && xx < n && yy < m && !vvis[xx][yy] && gra[xx][yy] != '#') {
vvis[xx][yy] = true;
cnt++;
que[tail++] = make_pair(xx, yy);
}
}
}
return cnt;
} void update(const string& s) {
int len1 = s.size(), len2 = ans.size();
if (len2 < len1 || (len2 == len1 && ans < s)) ans = s;
} void dfs(int x,int y,string s,int deep) {
int hh = h(x, y);
int l = ans.size();
if (deep + hh < l) return;
if (deep + hh == l) {
if (s + "z" < ans) return;
} update(s); for (int i = ; i < ; i++) {
int xx = x + dx[i], yy = y + dy[i];
if ( <= xx && <= yy && xx < n && yy < m && !vis[xx][yy] && gra[xx][yy] != '#') {
vis[xx][yy] = true;
dfs(xx, yy, s + gra[xx][yy], deep + );
vis[xx][yy] = false;
}
}
} int main()
{
//freopen("input.txt", "r", stdin);
while (~scanf("%d%d", &n, &m) && (n || m)) {
ans = "";
for (int i = ; i < n; i++) {
scanf("%s", gra[i]);
} for (int i = ; i < n; i++) {
for (int j = ; j < m; j++) {
if (isdigit(gra[i][j])) {
tmp = "";
tmp += gra[i][j];
vis[i][j] = true;
dfs(i, j, tmp, );
vis[i][j] = false;
}
}
}
cout << ans << endl;
}
return ;
}