zoukankan      html  css  js  c++  java
  • SRM 576 D2 L2:ArcadeManao,DFS,善于根据实际问题使用最简便的方法

    题目来源: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 ************************/
    


  • 相关阅读:
    [译]K-D-B-tree(草稿,第一次翻译)
    [LeetCode]Letter Combinations of a Phone Number
    [LeetCode]Multiply Strings
    [LeetCode]Populating Next Right Pointers in Each Node
    [LeetCode]Sum Root to Leaf Numbers
    [LeetCode]String to Integer (atoi)
    [LeetCode]Path Sum II
    [LeetCode]Minimum Depth of Binary Tree
    线上死锁问题排查
    Redis(四):独立功能的实现
  • 原文地址:https://www.cnblogs.com/bbsno1/p/3253905.html
Copyright © 2011-2022 走看看