There is a ball in a maze with empty spaces (represented as 0) and walls (represented as 1). The ball can go through the empty spaces by rolling up, down, left or right, but it won’t stop rolling until hitting a wall. When the ball stops, it could choose the next direction.
Given the m x n maze, the ball’s start position and the destination, where start = [startrow, startcol] and destination = [destinationrow, destinationcol], return true if the ball can stop at the destination, otherwise return false.
You may assume that the borders of the maze are all walls (see examples).
int n = maze.size(), m = maze[0].size(); int dx[4] = {0,1,0,-1}, dy[4] = {-1,0,1,0}; maze[start[0]][start[1]] = -1; queue<vector<int>> q; q.push(start); while(!q.empty()) { auto pos = q.front(); q.pop(); int y = pos[0], x = pos[1]; for(int i = 0; i < 4; i++) { int ny = y, nx = x;
while(0 <= ny + dy[i] and ny + dy[i] < n and0 <= nx + dx[i] and nx + dx[i] < m and maze[ny + dy[i]][nx + dx[i]] <= 0) { //move straight ny += dy[i]; nx += dx[i]; } if(!maze[ny][nx]) { maze[ny][nx] = -1; q.push({ny,nx}); if(destination[0] == ny and destination[1] == nx) returntrue; } } } returnfalse; } };