多校第四场 1009 hdu 5335 Walk Out(bfs+贪心)

题目连接:

hdu 5335

题目大意:

给出一个01矩阵,从左上角走到右下角,标记路径,问路径得到的二进制数最小是多少?

题目分析:

  1. 利用bfs找出到达右下角的曼哈顿距离最近的为0的点,因为当出现1之后,一定是通过曼哈顿路径才能得到最小解,因为任何多余的路径都会导致数位变多,而导致数大于路径短于当前路径组成的所有的数
  2. 然后之后一定是走曼哈顿路径,我们将整个矩形按照横纵坐标之和分层,那么可以贪心的解。因为某一层只要出现0,那么如果走为1的点一定会大于走0的点,因为数位的长度已经确定,所以如果某一层有0,那么只走0,直接输出0,如果没有0,直接输出1,再找下一层

代码如下:

#include <cstdio>
#include <algorithm>
#include <queue>
#include <cstring>
#define MAX 1007

using namespace std;

typedef pair<int,int> PII;
int t,n,m,h;
char mp[MAX][MAX];
bool mark[MAX][MAX];
int dx[]={0,1,0,-1};
int dy[]={1,0,-1,0};

bool bfs ( )
{
    h = -1;
    queue<PII> q;
    memset ( mark , 0 , sizeof ( mark ));
    mark[0][0] = true;
    if ( mp[0][0] == '1' ) return false;
    else h = 0;
    q.push ( make_pair ( 0 , 0 ));
    while (!q.empty())
    {
        int x = q.front().first;
        int y = q.front().second;
        q.pop();
        for ( int i = 0 ; i < 4 ; i++ )
        {
            int u = x+dx[i];
            int v = y+dy[i];
            if ( u < 0 || v < 0 || u >= n || v >= m ) continue;
            if ( mark[u][v] ) continue;
            if ( mp[u][v] == '1') continue;
            h = max ( u+v , h );
            q.push ( make_pair ( u , v ));
            mark[u][v] = true;
        }
    }
    return h == n+m-2;
}

void solve ( )
{
    bool flag = false;
    bool start = false;
    for ( int i = h; i < n+m-2 ; i++ )
    {
        flag = false;
        for ( int x = max ( 0 , i-m+1 ); x < n && x <= i; x++ )
        {
            int y = i-x;
            if ( !mark[x][y] ) continue;
            for ( int k = 0 ; k < 2 ; k++ )
            {
                int u = x+dx[k];
                int v = y+dy[k];
                if ( u < 0 || v < 0 || u >= n || v >= m ) continue;
                if ( mp[u][v] == '0' )
                {
                    flag = true;
                    mark[u][v] = 1;
                }
            }
        }
        if ( flag )
        {
            putchar ( '0' );
            continue;
        }
        else
            putchar ( '1' );
        for ( int x = max ( 0 , i-m+1); x < n && x <= i ; x++ )
        {
            int y = i-x;
            if (!mark[x][y] ) continue;
            for ( int k = 0 ; k < 2 ; k++ )
            {
                int u = x+dx[k];
                int v = y+dy[k];
                if ( u < 0 || v < 0 || u >= n || v >= m ) continue;
                mark[u][v] = 1;
            }
        }
    }
}

int main ( )
{
    scanf ( "%d" , &t );
    while ( t-- )
    {
        scanf ( "%d%d" , &n , &m );
        for ( int i = 0 ; i < n ; i++ )
            scanf ( "%s" , mp[i] );
        if ( bfs())
        {
            puts ( "0" );
            continue;
        }
        solve ();
        puts ("");
    }
}

你可能感兴趣的:(bfs,贪心)