-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBFS4WarKuWalk.py
More file actions
73 lines (68 loc) · 1.92 KB
/
BFS4WarKuWalk.py
File metadata and controls
73 lines (68 loc) · 1.92 KB
1
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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
'''
@Author - ReiiYuki
'''
import random
import queue
def randomMapCreate(size,obstacle) :
list = []
for i in range(0,size) :
list.append([])
for j in range(0,size) :
list[i].append(0)
for i in range(0,obstacle) :
x = random.randint(0,size-1)
y = random.randint(0,size-1)
list[x][y] = 1
return list
def printMap(map) :
for i in map :
for j in i :
print (j,end = " ")
print()
def BFS(map,x,y,targetX,targetY) :
history = dict()
s = []
q = queue.Queue()
s.append((x,y))
q.put((x,y))
reach = False
while q.qsize() > 0 or not reach:
current = q.get()
x = current[0]
y = current[1]
if current[0] == targetX and current[1] == targetY :
reach = True
s.append((x,y))
else :
if (x+1,y) not in s and x+1<len(map) and map[x+1][y] != 1 :
s.append((x+1,y))
q.put((x+1,y))
history[(x+1,y)] = current
if (x-1,y) not in s and x-1>=0 and map[x-1][y] != 1:
s.append((x-1,y))
q.put((x-1,y))
history[(x-1,y)] = current
if (x,y+1) not in s and y+1<len(map) and map[x][y+1] != 1:
s.append((x,y+1))
q.put((x,y+1))
history[(x,y+1)] = current
if (x,y-1) not in s and y-1>=0 and map[x][y-1] != 1:
s.append((x,y-1))
q.put((x,y-1))
history[(x,y-1)] = current
path = []
path.append((targetX,targetY))
current = (targetX,targetY)
while current in history :
current = history[current]
path.append(current)
return path[::-1]
def showWalk(map,path) :
for i in path :
map[i[0]][i[1]] = '*'
printMap(map)
print ()
map = randomMapCreate(16,50)
printMap(map)
path = BFS(map,0,8,15,15)
showWalk(map,path)