RQNOJ 83: World of Warcraft
RQNOJ 83
My Interpretation
Bob is on a very bizarre grid. Each cell of the N by M grid has either a 0, a 1, or a letter on it. If it is a 0, he can step on it. If it is a 1 - he can't step on it, for he would fall off the grid. A letter would immediately transport him to the matching letter - there is always one an only one matching letter to any letter. Once he is transported forward, he can't be transported back in the same move. He has a map of the grid, and wants to know if he can get to the opposite corner - he's standing at (1,1) and he's trying to get to (N, M). (1,1) and (N,M) are guaranteed to not be marked 1 or a letter. Calculate the least number of steps he has to take to reach (N, M)!
The Algorithm
This clearly is a shortest path problem - "least number of steps" - but it also appears to only ask for the distance between two points. This shows that this problem can be solved with breadth-first search. In the input, we make a array of 4-element arrays. Let a portal be represented by a pair of coordinates, i.e. a portal is (x1, y1, x2, y2). We store these 4 numbers in the 4-element arrays. When we parse a letter from the map, we mark the corresponding portal's x1 and y1 with the row and column of the portal, unless they are already marked in which we instead mark x2 and y2. So, during the BFS search, if a cell is marked a letter, we search it up and find whether or not it matched (x1, y1) or (x2, y2). Then, the values are switched, i.e. if the row is x2 and the column is y2 then the row is x1 and the column is y1.
Then, there's the question of where to put the "visited" tag on. The problem says "he can't be transported back in the same move". Does that restrict the possibility of using a portal more than twice? Absolutely not! If we want to go back to the exit portal so that we can continue down the no-portal path (e.g. a portal is smack in the middle of a path to the destination), we need to use a portal twice. Therefore, it is the best to instead mark "visited" on the entrance portal.
Then, there's the question of where to put the "visited" tag on. The problem says "he can't be transported back in the same move". Does that restrict the possibility of using a portal more than twice? Absolutely not! If we want to go back to the exit portal so that we can continue down the no-portal path (e.g. a portal is smack in the middle of a path to the destination), we need to use a portal twice. Therefore, it is the best to instead mark "visited" on the entrance portal.
Common Pitfalls
Linux considers line ends as "\n" whereas Windows considers line ends as "\r\n". When you aren't sure of the target operating system, use a safe method. For example, use cin for input.
IMPORTANT: If you use cin, REMEMBER ios_base::sync_with_stdio(false).
Comments
Post a Comment