snakes and ladders

來源:互聯網
上載者:User

蛇和梯子的遊戲。網上還木有這個題。…………

#include <iostream>#include <stdio.h>#include <string.h>#include <queue>#include <stdlib.h>using namespace std;bool visitFlag[10001]; //該位置是否到達過int snakeFlag[10001]; //此處是否有蛇頭int ladderFlag[10001]; //此處是否有梯子int end;//用滾動數組int bfs(queue<int> q[2]){int a = 0, b = 1;int step = 0;while (!q[a].empty()){swap(a, b);step++; //當前步數加1while (!q[b].empty()){int cur = q[b].front();q[b].pop();if (cur == end)return step - 1;for (int i = 1; i <= 6; i++){if (cur + i == end)return step;if (cur + i <= end && !visitFlag[cur+i]){//無論是到蛇頭,或是梯子處,都等於同時訪問了兩處int temp = snakeFlag[cur + i];if(temp > 0 && !visitFlag[temp]){if(temp == end)return step;visitFlag[temp] = true;q[a].push(temp);}else{temp = ladderFlag[cur + i];if(temp > 0 && !visitFlag[temp]){if(temp == end)return step;visitFlag[temp] = true;q[a].push(temp);}else{q[a].push(cur + i);}}visitFlag[cur + i] = true;}}}}return 0;}int main(){int k;cin >> k;int N, S, L;while (k--){scanf("%d %d %d", &N, &S, &L);int a, b;end = N * N;memset(visitFlag, 0, sizeof(visitFlag));memset(snakeFlag, 0, sizeof(snakeFlag));memset(ladderFlag, 0, sizeof(ladderFlag) );for (int i = 0; i < S; i++){cin >> a >> b;snakeFlag[a] = b;}for (int i = 0; i < L; i++){cin >> a >> b;ladderFlag[a] = b;}queue<int> q[2];q[0].push(1);cout << bfs(q) << endl;system("pause");}return 0;}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.