bfs
#include <bits/stdc++.h>
const int maxn = 100;
using namespace std;
int n, m, t;
bool hasDanger[maxn + 10][maxn + 10];
int danger[maxn + 10][maxn + 10][2];
struct tNode
{
int r, c;
int time;
tNode(int rr, int cc, int ttime):r(rr), c(cc), time(ttime){}
};
int vis[maxn + 10][maxn + 10][310];
int main()
{
scanf("%d%d%d", &n, &m, &t);
memset(hasDanger, 0, sizeof(hasDanger));
for (int i = 1, r, c, a, b; i <= t; i++)
{
scanf("%d%d%d%d", &r, &c, &a, &b);
hasDanger[r][c] = true;
danger[r][c][0] = a;
danger[r][c][1] = b;
}
memset(vis, 0, sizeof(vis));
queue<tNode> q;
q.push(tNode(1, 1, 0));
vis[1][1][0] = 1;
while (true)
{
tNode x = q.front(); q.pop();
int r = x.r, c = x.c, time = x.time;
// printf("bfs: %d %d %d
", r, c, time);
if (r == n && c == m)
{
printf("%d
", time);
break;
}
if (r <= n - 1 && !vis[r + 1][c][time + 1] && (!hasDanger[r + 1][c] || !(danger[r + 1][c][0] <= time + 1 && danger[r + 1][c][1] >= time + 1)))
q.push(tNode(r + 1, c, time + 1)), vis[r + 1][c][time + 1] = 1;
if (c <= m - 1 && !vis[r][c + 1][time + 1] && (!hasDanger[r][c + 1] || !(danger[r][c + 1][0] <= time + 1 && danger[r][c + 1][1] >= time + 1)))
q.push(tNode(r, c + 1, time + 1)), vis[r][c + 1][time + 1] = 1;
if (r >= 2 && !vis[r - 1][c][time + 1] && (!hasDanger[r - 1][c] || !(danger[r - 1][c][0] <= time + 1 && danger[r - 1][c][1] >= time + 1)))
q.push(tNode(r - 1, c, time + 1)), vis[r - 1][c][time + 1] = 1;
if (c >= 2 && !vis[r][c - 1][time + 1] && (!hasDanger[r][c - 1] || !(danger[r][c - 1][0] <= time + 1 && danger[r][c - 1][1] >= time + 1)))
q.push(tNode(r, c - 1, time + 1)), vis[r][c - 1][time + 1] = 1;
}
return 0;
}