Given with a matrix NxM
. There are '.' - cells you can visit, and '#' - cells you can't visit. You can only go up, down, right and left (not diagonal). Also given q
request, in each there are row and column of a cell needed to swap (if cell is '#' change it to '.' and vise versa). For each q
requests you print 'Yes' if it is possible to get from cell (sx, sy) to cell (tx, ty), and 'No' if not possible. It is givethat (sx, sy) and (tx, ty) are not '#' at any request.
In first line given sx, sy, tx, ty, N, M, q (every one of them is from 1 to 100). In the next N rows given a matrix with '.' being empty cell and '#' being a wall. After these N rows there are q rows with request. Each one is a pair of numbers descrbing x and y position in matrix to swap.
In the output there should be q rows, each having 'Yes' if it is possible to get from start point to target point at te step of the row, or 'No' if it is not possible.
Example: (Input)
1 1 2 3 3 3 2
.##
##.
###
1 2
2 2
(Output)
No
Yes
Explanation
After first request the matrix is
..#
##.
###
After the second request the matrix is
..#
#..
###
Unfortunately, I don't have the any more inpu examples. However, I have to pass all the unknown test on a website. There I solve all tests right except the two where I got time limit error. Maybe you can see hwo to speed up my code. By the way, the time limit is 0.5 second
My code is here:
sx, sy, tx, ty, n, m, q = map(int, input().split())
arr = [[] for i in range(n)]
for i in range(n):
line = input()
arr[i] = [1 if j=='.' else 0 for j in line]
change = [[] for i in range(q)]
for i in range(q):
change[i] = list(map(int, input().split()))
def is_path(sx, sy, tx, ty, gr):
visited = []
path = False
def dfs(px, py):
global path
if (px, py) == (tx, ty):
return True
visited.append([px, py])
for dx in [1, -1]:
if -1<py+dx<n and gr[px+dx][py] == 1 and [px+dx, py] not in visited:
if dfs(px+dx, py):
return True
for dy in [1, -1]:
if -1<py+dy<m and gr[px][py+dy] == 1 and [px, py+dy] not in visited:
if dfs(px, py+dy):
return True
return False
return dfs(sx, sy)
for i in range(q):
arr[change[i][0]-1][change[i][1]-1] += 1
arr[change[i][0] - 1][change[i][1] - 1] %= 2
ans = is_path(sx-1, sy-1, tx-1, ty-1, arr)
if ans: print('Yes')
else: print('No')