-
Notifications
You must be signed in to change notification settings - Fork 0
/
Escape maze
110 lines (107 loc) · 2.18 KB
/
Escape maze
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
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
typedef struct TPosition
{
int row, col;
int step; //number of moving steps to reach the current position from the start position
}Position;
typedef struct TNode
{
Position position;
struct TNode* next;
}Node;
Node *head, *tail = NULL;
int dr[4] = {0,0,1,-1};
int dc[4] = {1,-1,0,0};
int n,m;
int A[1000][1000];
int start_row; int start_col;
int visited[1000][1000]; //visited[r][c] = 1 khi ô (r,c) đã đi qua rồi
int queueEmpty()
{
return head == NULL && tail == NULL;
}
Node* makeNode(int r, int c, int step)
{
Node* p = (Node*)malloc(sizeof(Node));
(p->position).row = r;
(p->position).col = c;
(p->position).step = step;
p->next = NULL;
return p;
}
void PUSH(int r, int c, int step)
{
Node *p = makeNode(r,c,step);
if (head == NULL)
{
head = p;
tail = p;
return;
}
tail->next = p;
tail = p;
}
Position pop()
{
Node* tmp = head;
Position pos = head->position;
head = head->next;
if(head==NULL) tail = NULL;
free(tmp);
return pos;
}
int FinalPosition(int r, int c)
{
return r<1||r>n||c<1||c>m;
}
int check(int r, int c)
{
return A[r][c] == 0 && !visited[r][c];
}
int solve()
{
for (int i=0; i<1000; i++)
for (int j=0; j<1000; j++)
visited[i][j] =0;
PUSH(start_row,start_col,0);
visited[start_row][start_col] = 1;
while (!queueEmpty())
{
Position p = pop();
for (int k = 0; k < 4; k++)
{
int new_row = p.row+dr[k];
int new_col = p.col+dc[k];
if (FinalPosition(new_row,new_col))
{
return p.step+1;
}
if (check(new_row,new_col))
{
PUSH(new_row,new_col,p.step+1);
visited[new_row][new_col] = 1; //mark the position
}
}
}
return -1;
}
void input()
{
scanf("%d%d%d%d", &n, &m, &start_row, &start_col);
for (int i=1; i<=n; i++)
{
for(int j=1; j<=m; j++)
{
scanf("%d", &A[i][j]);
}
}
}
int main()
{
input();
int ans = solve();
printf("%d", ans);
return 0;
}