def isPossible(a,b):
global maps
rowSize= len(maps)
nSize= len(maps[0])
if a < rowSize and a >= 0 and b < nSize and b >= 0 and maps[a][b]==1:
maps[a][b]=2
return True
return False
def bfs():
global maps
rowSize= len(maps)
nSize= len(maps[0])
stack = [(0,0,0)]
while stack:
i,j,count= stack.pop(0)
count+=1
if i==rowSize-1 and j==nSize-2: return count
if i==rowSize-2 and j==nSize-1: return count
if isPossible(i-1,j):
stack.append((i-1,j,count))
if isPossible(i+1,j):
stack.append((i+1,j,count))
if isPossible(i,j-1):
stack.append((i,j-1,count))
if isPossible(i,j+1):
stack.append((i,j+1,count))
return count+3
return -1
def solution(m):
global maps
maps = m
rowSize= len(maps)
nSize= len(maps[0])
if nSize == 1 and rowSize == 1 and maps[0][0]==1: return 1
if nSize == 1 and rowSize == 1 and maps[0][0]==0: return -1
if maps[rowSize-1][nSize-2]==0 and maps[rowSize-2][nSize-1]==0: return -1
depth = bfs()
return depth+1
'Computer Science > 알고리즘 ( Algorithm )' 카테고리의 다른 글
XX 알고리즘 문제 2 (0) | 2019.03.18 |
---|---|
XX 알고리즘 문제 1 (0) | 2019.03.18 |
Codility - OddOccurrencesInArray (0) | 2019.03.12 |
Codility - StoneWall (0) | 2019.03.11 |
Codility - Nesting (0) | 2019.03.11 |