算法十三

来源:互联网 发布:北京金税三期软件下载 编辑:程序博客网 时间:2024/04/29 17:38

小明的游戏

算法描述

  • 小明喜欢玩游戏,这个算法是关于游戏的。
  • 游戏中有n个地点,标记为0到n-1
  • 每个地点有一个入口和一个出口
  • 输入为一个列表nextLevel,拥有n个元素
  • i代表i结点的入口,nextLevel[i]代表这i结点的出口
  • nextLevel[i]的值为-1时代表着小明赢的了该游戏
  • 小明从0结点开始玩游戏,一直走下去,若是最后走到-1,就赢了(输出“Win”),否则就是输了(输出“Lose”)

参数定义

  • 类名 DevuAndGame
  • 方法 canWin
  • 输入参数 vector <int>
  • 输出 string
  • 方法声明 string canWin(vector <int> nextLevel)

限制条件

  • nextLevel 包含[1, 50]个元素
  • nextLevel[i]的值为-1或者[0, n-1]中的某个值

例子

  • 输入
    • nextLevel: {1, -1}
  • 输出
    • ”Win”

小明从0结点开始. 出去后会到结点1,从结点1出来后会赢的游戏.

测试实例

  • 实例一
    • 输入
      • {1, 0, -1}
    • 输出
      • ”Lose”

小明会在0,1之间来回走,他无法走到结点2的出口.

  • 实例二

    • 输入
      • {0, 1, 2}
    • 输出
      • ”Lose”
  • 实例三

    • 输入
      • {29,33,28,16,-1,11,10,14,6,31,7,35,34,8,15,17,26,12,13,22,1,20,2,21,-1,5,19,9,18,4,25,32,3,30,23,10,27}
    • 输出
      • ”Win”
  • 实例四

    • 输入
      • {17,43,20,41,42,15,18,35,-1,31,7,33,23,33,-1,-1,0,33,19,12,42,-1,-1,9,9,-1,39,-1,31,46,-1,20,44,41,-1,-1,12,-1,36,-1,-1,6,47,10,2,4,1,29}
    • 输出
      • ”Win”
  • 实例五

    • 输入
      • {3, 1, 1, 2, -1, 4}
    • 输出
      • ”Lose”

代码

#include <iostream>#include <vector>using namespace std;class DevuAndGame {public:    string canWin(vector<int> nextLevel) {        /* if there's no '-1' in nextLevel, the game result must be lose */        bool exitEnd = false;        for(vector<int>::const_iterator iter = nextLevel.cbegin(); iter < nextLevel.cend(); iter++) {            if(-1 == *iter) {                exitEnd = true;                break;            }        }        if(!exitEnd)            return "Lose";        /* if the route comes back, the game will lose, otherwise, will it must reach '-1' finally */        vector<int> visitedNode;        bool comeBackFlag = false, reachEndFlag = false;        int i = 0;        // either of the flag is true , the game's result is judged        while(!comeBackFlag && !reachEndFlag) {            visitedNode.push_back(i);            for(vector<int>::const_iterator iter = visitedNode.cbegin(); iter < visitedNode.cend(); iter++) {                if(nextLevel[i] == *iter) {                    // the route truely come back, the game will lose                    comeBackFlag = true;                    break;                }            }            i = nextLevel[i];            if(-1 == i)                // reach the end, game will win                reachEndFlag = true;        }        if(comeBackFlag)            return "Lose";        else            return "Win";    }};int main() {    vector<int> nextLevel {29,33,28,16,-1,11,10,14,6,31,7,35,34,8,15,17,26,12,13,22,1,20,2,21,-1,5,19,9,18,4,25,32,3,30,23,10,27};    DevuAndGame dag;    string ret = dag.canWin(nextLevel);    cout << ret << endl;    cout.flush();}