hdoj 1254 推箱子 bfs嵌套
这题一边听着歌,一边做,结果相当悲剧。WA了无数次。。。。
看来BFS写得还是要规范点,这样细节上才能减少出错。
#include <iostream> #include <cmath> #include <queue> using namespace std; struct Position { int x, y; }; struct Status { Position person, box; int deep; }_s; int mp[10][10], n, m; int dir[4][2] = { 1, 0, 0, -1, -1, 0, 0, 1 }; Status person, box; Position end; void input() { int i, j; scanf( "%d %d", &n, &m ); for( i=0; i<n; ++i ) { for( j=0; j<m; ++j ) { scanf( "%d", &mp[i][j] ); if( mp[i][j] == 2 ) { _s.box.x = i; _s.box.y = j; } else if( mp[i][j] == 4 ) { _s.person.x = i; _s.person.y = j; } } } } inline bool isBond( Position p ) { if( p.x < 0 || p.y < 0 || p.x >= n || p.y >= m || mp[p.x][p.y] == 1) return 1; return 0; } bool canPush(Position pp, Status s) { queue<Position> Q; bool mark[10][10]; Position p, q; int i; memset( mark, 0, sizeof(mark)); Q.push( pp ); mark[pp.x][pp.y] = 1; mark[s.box.x][s.box.y] = 1; while( !Q.empty() ) { p = Q.front(); Q.pop(); if( p.x == s.person.x && p.y == s.person.y ) return 1; for( i=0; i<4; ++i ) { q = p; q.x += dir[i][0]; q.y += dir[i][1]; if( isBond(q) || mark[q.x][q.y] ) continue; mark[q.x][q.y] = 1; Q.push( q ); } } return 0; } int canReach() { queue<Status> Q; bool mark[10][10][4]; Status p, q; Position pp; int i; memset( mark, 0, sizeof(mark)); _s.deep = 0; Q.push( _s ); while( !Q.empty() ) { p = Q.front(); Q.pop(); if( mp[p.box.x][p.box.y] == 3 ) return p.deep; for( i=0; i<4; ++i ) { q.box.x = p.box.x + dir[i][0]; q.box.y = p.box.y + dir[i][1]; q.deep = p.deep + 1; if( isBond(q.box) || mark[q.box.x][q.box.y][i] ) continue; pp.x = p.box.x - dir[i][0]; pp.y = p.box.y - dir[i][1]; if( isBond( pp ) || !canPush(pp, p) ) continue; q.person = p.box; mark[q.box.x][q.box.y][i] = 1; Q.push( q ); } } return -1; } int main() { // freopen( "c:/aaa.txt", "r", stdin ); int T; scanf( "%d", &T ); while( T-- ) { input(); printf( "%d\n", canReach() ); } return 0; }
.