좌선법(왼쪽벽만 짚고 전진)으로 미로찾기
# https://www.acmicpc.net/problem/2178
# import sys
# sys.setrecursionlimit(100000)
#좌선법 ( Left Hand on Wall )
# while(still_in_maze):
# turn_left
# while(wall_ahead): #벽이 앞에 있다면
# turn_right
# go_ahead
n, m = map(int, input().split()) #n은 row ,m은 col
maze = []
for i in range(n):
maze.append(list(input()))
dir=['up','right','down','left']
dr=[0,1,1,0]
dc=[1,0,0,-1]
count=1
min=n*m
visited=[[0]*m for i in range(n)]
print(maze)
def stillInMaze(row,col):
if row <0 or col <0 or row >= n or col >= m:#map에서 벗어날경우 return
return False
else:
return True
def turnLeft(current_dir):
next_dir_index=dir.index(current_dir)-1
next_dir=dir[next_dir_index]
print(current_dir,next_dir)
return next_dir
def wallAhead(row,col,current_dir):
if current_dir=='up':
row=row-1
if row<0 or maze[row][col]=='0': #벽이거나 maze밖이라면
return True
else:
return False
elif current_dir=='left':
col=col-1
if col<0 or maze[row][col]=='0':
return True
else:
return False
elif current_dir=='down':
row=row+1
if row>=n or maze[row][col]=='0': #벽이거나 maze밖이라면
return True
else:
return False
elif current_dir=='right':
col=col+1
if col>=m or maze[row][col]=='0': #벽이거나 maze밖이라면
return True
else:
return False
def turnRight(current_dir):
next_dir_index=(dir.index(current_dir)+1)%4
next_dir=dir[next_dir_index]
print(current_dir,next_dir)
return next_dir
def goAhead(row,col,current_dir):
if current_dir=='up':
row=row-1
return row,col
elif current_dir=='left':
col=col-1
return row,col
elif current_dir=='down':
row=row+1
return row,col
elif current_dir=='right':
col=col+1
return row,col
def leftHand(row,col):
global count
current_dir=dir[2] #down
while(stillInMaze(row,col)):
current_dir=turnLeft(current_dir)
while(wallAhead(row,col,current_dir)):
current_dir=turnRight(current_dir)
row,col=goAhead(row,col,current_dir)
print(row,col)
count+=1
if row==n-1 and col==m-1:
print(count)
break
return
if __name__=="__main__":
#print(maze)
leftHand(0,0)
print(count)
# 4 6
# 0 101111
# 1 101010
# 2 101011
# 3 111011