第一道廣度搜索BFS紀念 poj 3278 源代碼
參考了別人的思路,做出了第一道BFS,雖然在大牛們看來不屑一顧,but about me,I really happy for it, I'm coming ! worm never give up!!
1
//============================================================================
2
// Name : poj.cpp
3
// Author :
4
// Version :
5
// Copyright : Your copyright notice
6
// Description : Hello World in C++, Ansi-style
7
//============================================================================
8
9
#include <iostream>
10
#include <queue>
11
using namespace std;
12
queue<int> q;
13
int result[100001];
14
int visited[100001] =
{0};
15
int BFS(int start,int end)
{
16
if (start == end)
17
return 0;
18
q.push(start);
19
result[start] = 0;
20
visited[start] = 1;
21
while(!q.empty())
{
22
int temp = q.front();
23
q.pop();
24
int next;
25
for (int i = 0; i < 3; ++i)
{
26
if (i == 0)
27
next = temp - 1;
28
if (i == 1)
29
next = temp + 1;
30
if (i == 2)
31
next = temp*2;
32
if(next > 100000 || next < 0)
{
33
continue;
34
}
35
if (visited[next] != 1)
{
36
q.push(next);
37
result[next] = result[temp] + 1;
38
visited[next] = 1;
39
}
40
if (next == end)
41
return result[next];
42
}
43
}
44
return 0;
45
}
46
int main()
{
47
int n,k;
48
cin >> n >> k;
49
cout << BFS(n,k) << endl;
50
return 0;
51
}
52

2

3

4

5

6

7

8

9

10

11

12

13

14



15



16

17

18

19

20

21



22

23

24

25



26

27

28

29

30

31

32



33

34

35



36

37

38

39

40

41

42

43

44

45

46



47

48

49

50

51

52
