-
Notifications
You must be signed in to change notification settings - Fork 0
/
04C2.c
137 lines (111 loc) · 2.64 KB
/
04C2.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define N 7
#define QUEUESIZE 2*1024*1024
typedef struct cost elementtype;
struct cost{
int x;
int y;
int c;
};
struct queue{
int front, rear;
elementtype elements[QUEUESIZE];
};
void initqueue(struct queue *q){
q->front = q->rear = 0;
}
int queueempty(struct queue *q){
return (q->front==q->rear);
}
void putq(struct queue *q, elementtype x){
q->elements[q->rear] = x;
q->rear++;
if(q->rear >= QUEUESIZE) q->rear=0;
if(q->rear == q->front){
printf("queue overflow\n"); exit(1);
}
}
elementtype getq(struct queue *q){
elementtype wk;
if(q->front==q->rear){
printf("queue underflow\n"); exit(1);
}
else{
wk=q->elements[q->front];
q->front++;
if(q->front >= QUEUESIZE) q->front = 0;
return wk;
}
}
int main(void){
#define BUFSIZE (N*2)
char buf[BUFSIZE];
char maze[N][N];
int i, j, sx, sy, gx, gy;
struct cost pos;
struct queue hoge;
struct cost tsugi;
for (i=0; i<N; i++){
fgets(buf, BUFSIZE, stdin);
for (j=0; j<N && (buf[j] != '\n' && buf[j] != '\0'); j++){
if(buf[j] == 'S'){
sx = j;
sy = i;
buf[j] = ' ';
}else if(buf[j] == 'G'){
gx = j;
gy = i;
buf[j] = ' ';
}
maze[i][j] = buf[j];
}
while(j<N) maze[i][j++] = ' ';
}
initqueue(&hoge);
pos.x = sx;
pos.y = sy;
pos.c = 0;
putq(&hoge, pos);
while(!queueempty(&hoge)){
pos = getq(&hoge);
if (pos.c == N * N){
pos.c = -1;
break;
}
if (pos.x == gx && pos.y == gy){
break;
}
maze[pos.y][pos.x] = '*';
if (maze[pos.y][pos.x - 1] == ' '){
tsugi.x = pos.x - 1;
tsugi.y = pos.y;
tsugi.c = pos.c + 1;
putq(&hoge, tsugi);
}
if (maze[pos.y][pos.x + 1] == ' '){
tsugi.x = pos.x + 1;
tsugi.y = pos.y;
tsugi.c = pos.c + 1;
putq(&hoge, tsugi);
}
if (maze[pos.y + 1][pos.x] == ' '){
tsugi.x = pos.x;
tsugi.y = pos.y + 1;
tsugi.c = pos.c + 1;
putq(&hoge, tsugi);
}
if(maze[pos.y - 1][pos.x] == ' '){
tsugi.x = pos.x;
tsugi.y = pos.y - 1;
tsugi.c = pos.c + 1;
putq(&hoge, tsugi);
}
}
if (pos.x != gx || pos.y != gy){
pos.c = -1;
}
printf("%d\n", pos.c);
return 0;
}