Pagini recente » Cod sursa (job #2487489) | Cod sursa (job #2345748) | Cod sursa (job #2051855) | Cod sursa (job #2180460) | Cod sursa (job #1757864)
#include <cstdio>
#include <deque>
const int MAX_N = 1000;
int dist[MAX_N + 2][MAX_N + 2];
const int EMPTY = 1;
const int WALL = 0;
int dLin[] = {0, 1, 0,-1};
int dCol[] = {1, 0,-1, 0};
struct coord {
int l, c, val;
};
int main() {
int n, m, l, c, lIn, cIn, lOut, cOut, i, lN, cN, val;
coord x;
std::deque<coord> d;
char ch;
FILE *fin = fopen("barbar.in", "r");
fscanf(fin, "%d%d", &n, &m);
for(l = 1; l <= n; l++) {
ch = fgetc(fin);
while(ch != '\n')
ch = fgetc(fin);
for(c = 1; c <= m; c++) {
ch = fgetc(fin);
if(ch == '.')
dist[l][c] = EMPTY;
else if(ch == 'D') {
dist[l][c] = WALL;
x.l = l;
x.c = c;
x.val = 0;
d.push_back(x);
} else if(ch == '*')
dist[l][c] = WALL;
else if(ch == 'I') {
lIn = l;
cIn = c;
dist[l][c] = EMPTY;
} else {
lOut = l;
cOut = c;
dist[l][c] = EMPTY;
}
}
}
fclose(fin);
while(d.size() > 0) {
l = d.front().l;
c = d.front().c;
val = d.front().val;
dist[l][c] = val;
d.pop_front();
for(i = 0; i < 4; i++) {
lN = l + dLin[i];
cN = c + dCol[i];
x.l = lN;
x.c = cN;
x.val = val + 1;
if(dist[lN][cN] == EMPTY) {
dist[lN][cN] = WALL;
d.push_back(x);
}
}
}
for(l = 0; l <= n + 1; l++)
dist[l][0] = dist[l][m + 1] = 0;
for(c = 0; c <= m + 1; c++)
dist[0][c] = dist[n + 1][c] = 0;
x.l = lIn;
x.c = cIn;
x.val = dist[lIn][cIn];
d.push_back(x);
dist[lIn][cIn] = 0;
do {
l = d.front().l;
c = d.front().c;
val = d.front().val;
d.pop_front();
for(i = 0; i < 4; i++) {
x.l = lN = l + dLin[i];
x.c = cN = c + dCol[i];
if(dist[lN][cN] > 0) {
if(dist[lN][cN] >= val) {
x.val = val;
d.push_front(x);
} else {
x.val = dist[lN][cN];
d.push_back(x);
}
dist[lN][cN] = -1;
}
}
} while((l != lOut || c != cOut) && d.size() > 0);
FILE *fout = fopen("barbar.out", "w");
if(l == lOut && c == cOut)
fprintf(fout, "%d", val);
else
fprintf(fout, "-1");
fclose(fout);
return 0;
}