USACO Gold 2017 January - Cow Navigation

Author: Michael Cao


In this problem, Bessie stands on a grid and wants to go from the lower left corner to upper-right corner in as few moves as possible. An initial idea could be to model the grid as a graph, where adjacent cells are connected by edges, and run a BFS to find the shortest path.

However, two additional constraints play a role in this problem: Bessie must be able to reach the destination regardless of which direction she starts in, and she can only move in the direction she is facing.

Let's imagine now that there are two cows standing on the cell (1,1)(1, 1), and both of them move the same way on each operation. Since N20N \leq 20, we can modify the original graph to support this new problem. Let's create a new graph GG' as follows:

For each pair of cells in the grid, (x,y)(x, y) and (x2,y2)(x_2, y_2), add 1616 nodes in the graph storing six parameters each:

  • xx coordinate of cow aa
  • yy coordinate of cow aa
  • xx coordinate of cow bb
  • yy coordinate of cow bb
  • direction of cow aa
  • direction of cow bb

for all 424 ^ 2 directions each cow could be facing.

Given this new graph, we add edges between two "states" which are reachable from each other. For example, if we apply the "turn left" operation, we add an edge to the state where both cows directions turn left.

On this new graph, we can directly run a BFS, and retrieve the answer at the state {N,N,N,N,x,y}\{N, N, N, N, x, y\} where xx and yy represent directions.

Warning!

Don't forget that once Bessie reaches the goal, she will ignore further commands. In the modified problem, if one of the two cows is at the goal, stop applying commands to her.

Implementation

C++

// created by Oleksandr Gorpynich
#include <bits/stdc++.h>
using ll = long long;
using namespace std;
int n;
struct state {
int x1;
int y1;
int x2;
int y2;

Join the USACO Forum!

Stuck on a problem, or don't understand a module? Join the USACO Forum and get help from other competitive programmers!