Given an n x n
matrix matrix
, which contains a single snake marked with ‘S’ cells, surrounded by ‘.’ cells, determine if the snake touches itself. The snake touches itself if there are at least two adjacent cells marked ‘S’ (horizontally or vertically) or any part of the snake forms a loop.
n
(size of the matrix)?
n
is guaranteed to be between 1 and 50 inclusive.True
if the snake touches itself, otherwise False
.def touches_itself(matrix):
n = len(matrix)
directions = [(-1, 0), (1, 0), (0, -1), (0, 1)]
# Find all 'S' cells
s_cells = [(i, j) for i in range(n) for j in range(n) if matrix[i][j] == 'S']
if not s_cells:
return False
# Check for adjacent 'S' cells
visited = set()
def dfs(x, y, parent):
# Mark the cell as visited
visited.add((x, y))
for dx, dy in directions:
nx, ny = x + dx, y + dy
if 0 <= nx < n and 0 <= ny < n and matrix[nx][ny] == 'S':
if (nx, ny) not in visited:
if dfs(nx, ny, (x, y)):
return True
elif (nx, ny) != parent:
# Found a loop
return True
return False
# Start DFS from the first 'S' cell
start_x, start_y = s_cells[0]
if dfs(start_x, start_y, None):
return True
return False
# Example test cases
matrix = [
['.', '.', '.', 'S', '.'],
['.', '.', 'S', 'S', '.'],
['.', '.', '.', 'S', '.'],
['.', '.', '.', '.', '.'],
['.', '.', '.', '.', '.']
]
print(touches_itself(matrix)) # Output: True
matrix = [
['.', '.', '.', '.', '.'],
['.', '.', 'S', 'S', '.'],
['.', '.', '.', 'S', '.'],
['.', '.', '.', '.', '.'],
['.', '.', '.', '.', '.']
]
print(touches_itself(matrix)) # Output: False
The space complexity is also (O(n^2)) due to the visited set for tracking the visited ‘S’ cells.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?