I'm having trouble with my homework assignment(C++). I'm not asking for the complete solution, but tilt in the right direction could be helpful. :)
I have a NxN board (max N = 100) and a 1x2 figure (cube) on that board. The cube is painted red on the one side and blue on the other. Default position for the cube is left upper angle of the board, blue side up:
B B . .
. . . .
. . . .
. . . .
(4x4 example, B stands for blue)
There could be stones (obstacles) on the blackboard. Moves I can make with my figure:
- rotating it for 90/180/270 degrees clockwise
- you can flip the cube around its right/left/upper/lower edge, changing its ''upward color''
For an example, using flip right on the default position:
. . R R
. . . .
. . . .
. . . .
and then using rotate 90:
. . R .
. . R .
. . . .
. . . .
and then using flip left:
. B . .
. B . .
. . . .
. . . .
Of course, when rotating or flipping, you cannot land on the stone. So, the problem is - for any given configuration of the board (figure position and stone positions) write a program that will ''bring the cube home'' in the default position (blue side upwards!) using minimal number of moves and return 1 if that's possible or return 0 if that's impossible.
I find this problem interesting, but I have to admit I'm slightly confused with it. Especially the blue side/red side part. I can't really figure out how to ''translate'' those moves I can use in the language of usual shortest path algorithms (and I never used any of these). So, I would be grateful for every piece of advice you can give! :)
When dealing with this kind of problems, the first thing to do is to find a representation of the state of your problem. In this case, you need:
If you are familiar with bitmasks, you should use just a 32 bit integer to do this (8 bits for x position, 8 bits for y position, 2 bits for the rest). In this way you don't need to implement a comparison operator. OR You define a simple struct (call it
state
) with these 3 information and a strict-ordering comparison on this (this is only needed to putstate
instd::set
.After this, you can solve this problem using a BFS.
To do that, you need:
std::map<state,state>
to store the position you already visited in the key, and the position you came from in the value (replacemap
withunordered_map
if you can use c++11 and you use a bitmask to store your state)std::queue<state>
in which push and pop up the states to be processed.Pseudo code:
The presence of obstacles make just the problem more difficult to code, but is no conceptually different.
Note that in this case BFS works because the cost you pay for going from one state to another is always the same.