您的位置:首页 > 其它

SRM 576 D2 L2:ArcadeManao,DFS,善于根据实际问题使用最简便的方法

2013-08-11 22:51 387 查看
题目来源:http://community.topcoder.com/stat?c=problem_statement&pm=12504

这是个典型的图论的题目,很容易就能把题目抽象的图论的描述:求连接两点的所有 路径中权值最大的边 的最小值。但求解起来非常麻烦。如果换一个角度来思考,根据实际题目的要求,只需要计算当梯子长度从 0 到 N-1 时起点和终点是否能够连通,那么最先符合条件的那个长度就是最短的长度。所以使用DFS求解是非常方便的。这道题目给我的启发就是要根据实际的题目描述来找到最适合题目的解,而不是盲目的抽象,泛化。就像刚看的编程珠玑的第一节中的那个排序问题,要善于根据实现的题目描述找到最优解。

代码如下:

#include <algorithm>
#include <iostream>
#include <sstream>

#include <string>
#include <vector>
#include <stack>
#include <deque>
#include <queue>
#include <set>
#include <map>

#include <cstdio>
#include <cstdlib>
#include <cctype>
#include <cmath>
#include <cstring>

using namespace std;

/*************** Program Begin **********************/
class ArcadeManao {
private:
bool v[50][50];
int M, N, L;
vector <string> lev;
void DFS(int x, int y)
{
v[x][y] = true;
// 左
if (y-1 >= 0 && 'X' == lev[x][y-1] && !v[x][y-1]) {
DFS(x, y-1);
}
// 右
if (y+1 <= M-1 && 'X' == lev[x][y+1] && !v[x][y+1]) {
DFS(x, y+1);
}
// 竖直方向
for (int i = 0; i < N; i++) {
if (abs(x-i) <= L && 'X' == lev[i][y] && !v[i][y]) {
DFS(i, y);
}
}
}
public:
int shortestLadder(vector <string> level, int coinRow, int coinColumn) {
int res = 0;
N = level.size();
M = level[0].size();
lev = level;

for (int i = 0; i < N; i++) {
memset(v, 0, sizeof(v));
L = i;
DFS(N-1, 0);
if (v[coinRow-1][coinColumn-1]) {
res = i;
break;
}
}
return res;
}
};

/************** Program End ************************/
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐