- import os
- import time
- import random
- global FIND
- global SCREEN
- FIND=0
- cols=22
- rows=22
- waypoint=[]
- target=(10,13)
- start=(1,1)
- SCREEN=[['' for x in range(cols)] for y in range(rows)]
- grid=[[0 for x in range(cols)] for y in range(rows)]
- for x in range(cols):
- grid[0][x]=1
- grid[rows-1][x]=1
- for y in range(rows):
- grid[y][0]=1
- grid[y][cols-1]=1
- grid[target[0]][target[1]]=2
-
- def show(sy,sx):
- for y in range(rows):
- for x in range(cols):
- if grid[y][x]==0:SCREEN[y][x]=' '
- if grid[y][x]==1:SCREEN[y][x]='*'
- if grid[y][x]==2:SCREEN[y][x]='1'
- if grid[y][x]==3:SCREEN[y][x]='x'
- SCREEN[sy][sx]='0'
- os.system('cls')
- for y in SCREEN:print(' '.join(y))
- time.sleep(0.1)
-
- def search(y,x):
- global FIND
- global SCREEN
- direct=random.randint(0,3)
- grid[y][x]=3
- waypoint.append((y,x))
- show(y,x)
- if grid[y][x+1]==2 or grid[y+1][x]==2 or grid[y-1][x]==2 or grid[y][x-1]==2:
- FIND=1
- return
- if direct==0:#向右顺时针搜索
- if grid[y][x+1]==0 and FIND==0:search(y,x+1)
- if grid[y+1][x]==0 and FIND==0:search(y+1,x)
- if grid[y][x-1]==0 and FIND==0:search(y,x-1)
- if grid[y-1][x]==0 and FIND==0:search(y-1,x)
- if direct==1:#向下顺时针
- if grid[y+1][x]==0 and FIND==0:search(y+1,x)
- if grid[y][x-1]==0 and FIND==0:search(y,x-1)
- if grid[y-1][x]==0 and FIND==0:search(y-1,x)
- if grid[y][x+1]==0 and FIND==0:search(y,x+1)
- if direct==2:#向左顺时针
- if grid[y][x-1]==0 and FIND==0:search(y,x-1)
- if grid[y-1][x]==0 and FIND==0:search(y-1,x)
- if grid[y][x+1]==0 and FIND==0:search(y,x+1)
- if grid[y+1][x]==0 and FIND==0:search(y+1,x)
- if direct==3:#向上顺时针
- if grid[y-1][x]==0 and FIND==0:search(y-1,x)
- if grid[y][x+1]==0 and FIND==0:search(y,x+1)
- if grid[y+1][x]==0 and FIND==0:search(y+1,x)
- if grid[y][x-1]==0 and FIND==0:search(y,x-1)
- if FIND==0:
- del waypoint[-1]
- show(waypoint[-1][0],waypoint[-1][1])
- else:
- print('blind 0 found 1!')
- os.system('pause >nul')
- os.system('cls')
- print("0's way of duplicate removal:")
- SCREEN=[[' 'for x in range(cols)] for y in range(rows)]
- i=1
- for point in waypoint:
- SCREEN[point[0]][point[1]]=('%3s'%(str(i)))
- i+=1
- for y in SCREEN:print(' '.join(y))
- os.system('pause >nul')
- exit()
-
- show(start[0],start[1])
- print("blind 0 want to find 1,press key to go...")
- os.system('pause >nul')
- search(start[0],start[1])
复制代码
|