1. 程式人生 > 其它 >【藍橋杯】2017初賽 跳蚱蜢(bfs,迴圈陣列)

【藍橋杯】2017初賽 跳蚱蜢(bfs,迴圈陣列)

技術標籤:演算法廣度搜索

如圖所示: 有9只盤子,排成1個圓圈。其中8只盤子內裝著8只蚱蜢,有一個是空盤。

在這裡插入圖片描述

我們把這些蚱蜢順時針編號為 1~8。每隻蚱蜢都可以跳到相鄰的空盤中,也可以再用點力,越過一個相鄰的蚱蜢跳到空盤中。
請你計算一下,如果要使得蚱蜢們的隊形改為按照逆時針排列,並且保持空盤的位置不變(也就是1-8換位,2-7換位,…),至少要經過多少次跳躍?

不要讓螞蚱移動,讓空盤子移動。那麼空盤子就有4種情況,可以很容易想到bfs。
要用到佇列(用來廣度優先搜尋),set(用來去重)。結構體過載其實可以不用,自己寫傳的值也可以。

這個程式碼執行超時,沒明白是什麼原因。


```cpp
#include<bits/stdc++.h>
using namespace std;

char *start = "012345678";
char *target = "087654321";

struct StateAndLevel{
	char *state;//狀態 
	int level;//層次
	int pos0;//零的位置 
	StateAndLevel(char*_state,int _level,int _pos0):state(_state),level(_level),pos0(_pos0){}
};//初始化列表
struct cmp{
	bool operator()(char* a,char* b){
		return strcmp(a,b)<0;
	}
};
queue<StateAndLevel> q;
set<char*,cmp>allState;

void swap(char *s,int a,int b){//交換函式 
	char t = s[a];
	s[a] = s[b];
	s[b] = t;
}
void addNei(char* state,int pos,int newPos,int le){
	char *new_state = (char*)malloc(9*sizeof(char));
	strcpy(new_state,state);
	swap(new_state,pos,newPos);
	if(allState.find(new_state) == allState.end()){
		allState.insert(new_state);
		q.push(StateAndLevel(new_state, le + 1,newPos));
	}
}
int main(){
	q.push(StateAndLevel(start,0,0));
	while(!q.empty()){
		StateAndLevel sal = q.front();
		char *state = sal.state;
		int le = sal.level;
		int pos0 = sal.pos0;
		allState.insert(state);
		if(strcmp(state,target) == 0){
			printf("%d",le);
			return 0;
		}
		int new_pos = (pos0 - 1 + 9) % 9;
		addNei(state, pos0, new_pos, le);
		new_pos = (pos0 + 1 + 9) % 9;
		addNei(state, pos0, new_pos, le);
		new_pos = (pos0 - 2 + 9) % 9;
		addNei(state, pos0, new_pos, le);
		new_pos = (pos0 + 2 + 9) % 9;
		addNei(state, pos0, new_pos, le);
		q.pop();
	}
}