Maze Traversal
Time Limit: 2 Seconds MemoryLimit: 65536 KB
Acommon problem in artificial intelligence is negotiation of a maze. A maze hascorridors and walls. The robot can proceed along corridors, but cannot gothrough walls.
Input
For this problem,you will input the dimensions of a maze, as two integer values on the firstline. Of the two numbers, the first is the number of rows and the second is thenumber of columns. Neither the number of rows nor columns will exceed 60.
Following thesenumbers will be a number of rows, as specified previously. In each row therewill be a character for each column, with the tow terminated by the end ofline. Blank spaces are corridors, asterisks are walls. There needn't be anyexits from the maze.
Following themaze, will be an initial row and column specified as two integers on one line.This gives the initial position of the robot. Initially the robot will befacing North (toward the first row).
The remaininginput will consist of commands to the robot, with any amount of interspersedwhite-space. The valid commands are:
R rotate the robot90 degrees clockwise (to the right)
L rotate the robot 90 degrees counter-clockwise (to the left)
F move the robot forward unless a wall prevents this in which case do nothing
Q quite the program, printing out the current robot row, column andorientation.
Process to the endof file.
Output
The final row andcolumn must be integers separated by a space. The orientation must be one of N,W, S, E and separated from the column by a space.
Sample Input
7 8
********
* * * **
* * *
* * ** *
* * * *
* * **
********
2 4
RRFLFF FFR
FF
RFFQ
Sample Output
5 6 W
————————————————————————————————————————————————————————————————
#include <stdio.h>
#include <string.h>
void turn(char *dir, char command);
void move(char dir, int * r, int * l);
char map[65][65];
int n, m;
int main()
{
int i, j;
int posr, posl;
char dir;
char command, str[65];
while(scanf("%d%d", &n, &m) != EOF) {
getchar();
for(i = 0; i < n; i++) {
gets(str);
for(j = 0; j < m; j++) {
map[i][j] = str[j];
}
}
scanf("%d%d", &posr, &posl);
posr -= 1;
posl -= 1;
dir = 'N';
while((command = getchar()) != 'Q') {
if(command == 'R' || command == 'L') {
turn(&dir, command);
}
else if(command == 'F') {
move(dir, &posr, &posl);
}
}
printf("%d %d %c\n", posr+1, posl+1, dir);
}
return 0;
}
void turn(char *dir, char command)
{
if(command == 'R') {
if(*dir == 'N') {
*dir = 'E';
}
else if(*dir == 'S') {
*dir = 'W';
}
else if(*dir == 'W') {
*dir = 'N';
} else {
*dir = 'S';
}
} else {
if(*dir == 'N') {
*dir = 'W';
}
else if(*dir == 'S') {
*dir = 'E';
}
else if(*dir == 'W') {
*dir = 'S';
} else {
*dir = 'N';
}
}
}
void move(char dir, int *r, int *l)
{
int tr, tl;
tr = *r;
tl = *l;
if(dir == 'N') {
tr -= 1;
}
else if(dir == 'S') {
tr += 1;
}
else if(dir == 'W') {
tl -= 1;
} else {
tl += 1;
}
if(tr >= 0 && tr < n && tl >= 0 && tl < m) {
if(map[tr][tl] == ' ') {
*r = tr;
*l = tl;
}
}
}