1381:Munching
Time Limit:1000MS Memory Limit:65536K
Total Submit:41 Accepted:25
Description
Bessie loves her grass and loves to hurry to the barn for her evening
milking session. She has partitioned the pasture into a rectilinear
grid of R (1 <= R <= 100) rows and C (1 <= C <= 100) columns and
marked the squares as grass or rocky (she can't eat rocks and won't
even go into those squares). Bessie starts on her map at location
R_b,C_b and wishes to munch her way, square by square, to the barn
at location 1,1 by the shortest route possible. She moves from one
square to any one of the potentially four adjacent squares.
Below is the original map [with rocks ('*'), grass ('.'), the barn
('B'), and Bessie ('C' for cow) at row 5, col 6] and a route map
with the optimal route marked with munches ('m'):
Map Optimal Munched Route
1 2 3 4 5 6 <-col 1 2 3 4 5 6 <-col
1 B . . . * . 1 B m m m * .
2 . . * . . . 2 . . * m m m
3 . * * . * . 3 . * * . * m
4 . . * * * . 4 . . * * * m
5 * . . * . C 5 * . . * . m
Bessie munched 9 squares.
Given a map, determine how many squares Bessie will eat on her
shortest route to the barn (there's no grass to eat on the barn's
square).
Input
* Line 1: Two space-separated integers: R and C
* Lines 2..R+1: Line i+1 describes row i with C characters (and no
spaces) as described above
Output
* Line 1: A single integer that is the number of squares of grass that
Bessie munches on the shortest route back to the barn
Sample Input
5 6
B...*.
..*...
.**.*.
..***.
*..*.C
Sample Output
9
Source
OPEN08
转移方向那里写得有点臃肿,不过这样显得更直观
#include<cstdio> #include<queue> #include<cstring> using namespace std; char map[110][110]; struct node { int x, y, step; }; int main() { int r, c, si, sj; queue<node> que; scanf("%d %d", &r, &c); for(int i = 0; i < r; i++) { scanf("%s", map[i]); for(int j = 0; j < c; j++) if(map[i][j] == 'C') { si = i; sj = j; map[i][j] = '*'; } } node s = {si, sj, 0}; que.push(s); while(!que.empty()) { node st = que.front(); que.pop(); if(st.x > 0 && map[st.x - 1][st.y] != '*') { if(map[st.x - 1][st.y] == 'B') { printf("%d/n", st.step + 1); return 0; } node ad = {st.x - 1, st.y, st.step + 1}; map[st.x - 1][st.y] = '*'; que.push(ad); } if(st.x + 1 < r && map[st.x + 1][st.y] != '*') { if(map[st.x + 1][st.y] == 'B') { printf("%d/n", st.step + 1); return 0; } node ad = {st.x + 1, st.y, st.step + 1}; map[st.x + 1][st.y] = '*'; que.push(ad); } if(st.y > 0 && map[st.x][st.y - 1] != '*') { if(map[st.x][st.y - 1] == 'B') { printf("%d/n", st.step + 1); return 0; } node ad = {st.x, st.y - 1, st.step + 1}; map[st.x][st.y - 1] = '*'; que.push(ad); } if(st.y + 1 < c && map[st.x][st.y + 1] != '*') { if(map[st.x][st.y + 1] == 'B') { printf("%d/n", st.step + 1); return 0; } node ad = {st.x, st.y + 1, st.step + 1}; map[st.x][st.y + 1] = '*'; que.push(ad); } } return 0; }