check 787. The Maze

Description

中文English
There is a ball in a maze with empty spaces and walls. The ball can go through empty spaces by rolling updownleft or rightbut it won't stop rolling until hitting a wall. When the ball stops, it could choose the next direction.
Given the ball's start position, the destination and the maze, determine whether the ball could stop at the destination.
The maze is represented by a binary 2D array. 1 means the wall and 0 means the empty space. You may assume that the borders of the maze are all walls. The start and destination coordinates are represented by row and column indexes.
1.There is only one ball and one destination in the maze.
2.Both the ball and the destination exist on an empty space, and they will not be at the same position initially.
3.The given maze does not contain border (like the red rectangle in the example pictures), but you could assume the border of the maze are all walls.
5.The maze contains at least 2 empty spaces, and both the width and height of the maze won't exceed 100.

Example

Given:
a maze represented by a 2D array

0 0 1 0 0
0 0 0 0 0
0 0 0 1 0
1 1 0 1 1
0 0 0 0 0

start coordinate (rowStart, colStart) = (0, 4)
destination coordinate (rowDest, colDest) = (4, 4)

Return:true

struct node{ int x; int y; node(int a, int b){ x = a; y = b; } }; bool hasPath(vector<vector<int>> &maze, vector<int> &start, vector<int> &destination) { // write your code here int m = maze.size(); if(m == 0){ return -1; } int n = maze[0].size(); vector<int> dx = {-1, 1, 0, 0}; vector<int> dy = {0, 0, -1, 1}; // define the left, right, up and down std::queue<node> q; int dis = 0; q.push(node(start[0], start[1])); while(!q.empty()){ int sizeQ = q.size(); dis++; for(int i = 0; i < sizeQ; i++){ node temp = q.front(); q.pop(); maze[temp.x][temp.y] = 2; // flag the visited position for(int i = 0; i < 4; i++){ int newX = temp.x + dx[i]; int newY = temp.y + dy[i]; while(!canStop(maze, newX, newY)){// judge when to stop newX += dx[i]; newY += dy[i]; } newX -= dx[i]; newY -= dy[i]; if(maze[newX][newY] != 2){ if(newX == destination[0] && newY == destination[1]){ return true; } q.push(node(newX, newY)); } } } } return false; } bool canStop(vector<vector<int>> &maze, int x, int y){ if(x < 0 || x >= maze.size() || y < 0 || y >= maze[0].size() || maze[x][y] == 1){ return true; } else{ return false; } }

Comments

Popular posts from this blog

1427. Split Array into Fibonacci Sequence

Amazon OA 763. Partition Labels

05/25 周一