/* 1997 East-Central ACM regional programming contest Held on November 8, 1997 Sample solution by Ed Karrels, Ed@tool.com November 1997 */ #include /* mark what cells have been visited. 0 = not visited -1 = visted, but backed out >0 = on the path to freedom */ int visited[12][12]; /* mark the walls in the maze, 1 bit = east wall, 2 bit = south wall */ int walls[12][12]; struct Position {int r, c;}; /* could go as deep as 12 x 12 = 144, add a little more for possible off-by-one error */ struct Position stack[150]; /* index of the _next_ position on the stack */ int stack_lvl; /* size of the maze */ int nrows, ncols; /* starting position */ int startrow, startcol; /* ending position */ int endrow, endcol; /* Recursive function. Called with a position in the maze to try. If this move leads to a successful path, return 1, otherwise 0. */ int Try(int row, int col) { struct Position p; /* if this cell is on the path (visited before but backed out counts as not visited) don't loop back onto myself */ if (visited[row][col] > 0) return 0; /* clearly, I wrote this in a hurry. A stack is not needed at all, because with the recursive function, the current position will be held in the local variables. duh. */ p.r = row; p.c = col; stack[stack_lvl++] = p; /* use the stack level to mark the position in the path */ visited[row][col] = stack_lvl; /* if done, return 1 */ if (row == endrow && col == endcol) return 1; /* search order: W N E S */ /* for each side, check if the current position is at the edge of the maze, or if there is a wall on that side. Don't bother checking if I've been to that cell already. Do that first thing when I get there; see above. */ if (col > 0 && !(walls[row][col-1] & 1)) /* west */ if (Try(row, col-1)) return 1; if (row > 0 && !(walls[row-1][col] & 2)) /* north */ if (Try(row-1, col)) return 1; if (col < ncols-1 && !(walls[row][col]&1)) /* east */ if (Try(row, col+1)) return 1; if (row < nrows-1 && !(walls[row][col]&2)) /* south */ if (Try(row+1, col)) return 1; visited[row][col] = -1; /* no luck; backtrack */ stack_lvl--; return 0; } int main() { int r, c; int maze_no=0; /* the debugger in Turbo/Borland C++ DOS IDE doesn't give you a way to read stdin from a file in debug mode. During testing, this line is: FILE *inf = fopen("prob_a.in", "r"); */ FILE *inf = stdin; do { fscanf(inf, "%d %d %d %d %d %d", &nrows, &ncols, &startrow, &startcol, &endrow, &endcol); /* the input counts starting at 1. Change to start at 0. */ startrow--; startcol--; endrow--; endcol--; /* if end of input, exit */ if (nrows == 0) return 0; printf("Maze %d\n\n", ++maze_no); /* clear the maze of my footprints */ for (r=0; r<12; r++) for (c=0; c<12; c++) visited[r][c] = 0; /* read in where the walls are */ for (r=0; r