码迷,mamicode.com
首页 > 其他好文 > 详细

HackerRank - Count Luck

时间:2015-04-27 14:51:51      阅读:106      评论:0      收藏:0      [点我收藏+]

标签:

Simplied a DFS\BFS with minor modification.

#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
#include <unordered_set>
using namespace std;

typedef vector<vector<char>> Matrix;
typedef pair<int, int> Pos;

bool isWay(Matrix &m, int i, int j)
{
    return m[j][i] == . || m[j][i] == *;
}

bool go(Matrix &m, Pos curr, Pos dst, const int k, int n)
{
    if (curr == dst)
    {
        return n == k;
    }

    int h = m.size();
    int w = m[0].size();

    int i = curr.first;
    int j = curr.second;
    vector<Pos> cands;
    if (i > 0 && isWay(m, i - 1, j))
    {
        cands.push_back(Pos(i - 1, j));
    }
    if (i < w - 1 && isWay(m, i + 1, j))
    {
        cands.push_back(Pos(i + 1, j));
    }
    if (j > 0 && isWay(m, i, j - 1))
    {
        cands.push_back(Pos(i, j - 1));
    }
    if (j < h - 1 && isWay(m, i, j + 1))
    {
        cands.push_back(Pos(i, j + 1));
    }
    if (cands.size() == 0) return false;

    int nn = cands.size() > 1 ? (n + 1) : n;
    for (auto &r : cands)
    {
        m[r.second][r.first] = X;
        if (go(m, r, dst, k, nn))
        {
            return true;
        }
    }
    return false;
}

int main()
{
    int n; cin >> n;
    while (n--)
    {
        int h, w; cin >> h >> w;

        Pos dst, start;
        Matrix mx(h, vector<char>(w, .));
        for (int j = 0; j < h; j ++)
        for (int i = 0; i < w; i++)
        {
            cin >> mx[j][i];
            switch(mx[j][i])
            {
            case M:
                start.first = i;
                start.second = j;
                break;
            case *:
                dst.first = i;
                dst.second = j;
                break;
            }
        
        }
        int k; cin >> k;
        bool bRet = go(mx, start, dst, k, 0);
        cout << (bRet ? "Impressed" : "Oops!") << endl;
    }
    return 0;
}

HackerRank - Count Luck

标签:

原文地址:http://www.cnblogs.com/tonix/p/4460082.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!