On Lamp Switch the Lamp On

https://loj.ac/problem/2632

Title Description

  Given oblique n rows and m columns, the requirements from the (0,0) come (n, m), down to only four oblique directions, the same direction to go when the oblique direction takes 0, otherwise spend 1.

Thinking

  Bfs more classic title, can be seen as 0,1 shortest address the double-ended queue. Deque is used in order to maintain monotonicity queue, step i.e. when certain elements of the queue from the tail to the head of the queue is monotonically increasing (but not strictly increasing). But this question there are some details that need attention.

   First you properly handle the relationship between the road and the point where to go clear need to see is that a slash.

   Second, an important point also mentioned in parentheses, due to the step is not strictly a single increase, so we do not use the storage array whether vis visited, for example, because we now spend to 0 (2,2), to the present, able to 1 went to the expense of (3,1), after a vis array record, from (2,0) to be able to come to a total consideration of (3,1), but because they have visited will be ignored. The minimum cost so we can store an array with a cost to the (x, y), more than the minimum if you can spend less.

Code

#include<bits/stdc++.h>
using namespace std;

struct aa
{
    int x,y,step;
    aa(int x=0,int y=0,int step=0):x(x),y(y),step(step) {}
};

int dx[4]={1,1,-1,-1},dy[4]={1,-1,1,-1};
int px[4]={0,0,1,1},py[4]={0,1,0,1};
char mp[550][550];
bool check(int x,int y,int t)
{
    if(mp[x][y]=='/')
    {
        if(t==0||t==3)return 1;
        else return 0;
    }
    else
    {
        if(t==0||t==3)return 0;
        else return 1;
    }
}
int cost[550][550]; 
int n,m;
bool valid(int x,int y){return x>=0&&y>=0&&x<=n&&y<=m;}
void bfs(int sx,int sy)
{
    memset(cost,0x3f,sizeof(cost));
    deque<aa>q;
    q.push_front(aa(sx,sy,0));
    cost[sx][sy]=0;
    while(!q.empty())
    {
        aa u=q.front();q.pop_front();
        if(u.x==n&&u.y==m)
        {
            printf("%d",u.step);
            return ;
        } 
        for(int i=0;i<4;i++)
        {
            int nx=u.x+dx[i];
            int ny=u.y+Dy [I];
             if (Valid (NX, NY)) 
            { 
                BOOL F = Check (NX + PX [I], NY + Py [I], I); // implemented by p array of slash and the transfer point 
                if (cost [NX] [NY] <= cost [UX] [UY] + F) Continue ; // comparison to the cost of this point, there is an equal sign 
                cost [nx] [ny] = cost [ux] [uy] + F;
                 IF (F) q.push_back (AA (NX, NY, u.step + . 1 )); // deque discharge head of the queue, the tail 
                the else q.push_front (AA (NX, NY, u.step)) ; 
            } 
        } 
    } 
    the printf ( " NO SOLUTION " ); 
} 

int main () 
{ 
    Scanf ("%d%d",&n,&m);
    for(int i=1;i<=n;i++)
        scanf(" %s",mp[i]+1);
    bfs(0,0);
}

 

Guess you like

Origin www.cnblogs.com/fangbozhen/p/11613997.html