#include #include #include enum { // Directions UP = 0, RIGHT, DOWN, LEFT, _COUNT, // Map elements EMPTY = '.', OBSTACLE = '#', GUARD = '^', VISITED = 'X', }; int main(void) { unsigned result; char map[256][256]; // Map with [y][x] coordinates int w,h; // Map size int x,y, dx,dy, dir; // Guard current and delta position and walking direction int gx,gy, ox,oy; // Guard original position and obstacle position // Get map with height and width for (h=0; fgets(map[h], sizeof map[0], stdin); h++); w = strlen(map[0]) -1; // -1 for '\n' character at the end of the line // Find guard starting position. for (gy=0; gy=0 && y=0) { if (map[y][x] == dir) { // I was already here walking in the // same direction. We found a loop. result++; break; } if (map[y][x] == EMPTY) { map[y][x] = dir; // Remember direction } switch (dir) { case UP: dx= 0; dy=-1; break; case RIGHT: dx=+1; dy= 0; break; case DOWN: dx= 0; dy=+1; break; case LEFT: dx=-1; dy= 0; break; } x+=dx; y+=dy; // Apply delta position if (map[y][x] == OBSTACLE) { x-=dx; y-=dy; // Go back one step dir = (dir+1) % _COUNT; // Turn right by switching to next direction } } // Restore map for (y=0; y