Maze and Treasure

description

Robot to act (can not stay in place, can only go on up / down / left / right) in a rectangular maze, each move one space to spend a unit of time.
Maze has the following elements:

[*] Starting point for robots

[#] Wall. These robots can not come grid

[.] The ground. The robot can walk freely on it

[0-9] treasures. When the robot came here immediately get the figures for the corresponding treasure, the treasure will not disappear, you can repeatedly get (but not stop)

If robots are to get exactly the sum of x treasures, and how much time it requires a minimum?

Entry

The first line number of the input task T, with T next task
first line of each block having two integers, n (0 <= n < 100), m (0 <= m <100), there are n + 1, the maze row and column m + 1

The next n input lines maze

The last line of input you want to collect the treasures of the total value of x (0 <= x ≤ 100)

 

Export

For each task, the output takes a minimum, if not to complete the task outputs -1

Sample input

3

2 3
1.#2
#..#
*.#.
3

2 3
2.#2
#..#
*.#.
5

2 3
2.#2
#.3#
*.#.
5

Sample Output

8
-1
6

Problem-solving ideas: It may be enumerated by bfs each for each location

#include <bits/stdc++.h>
using namespace std;
char s[105][105];
int vis[105][105][105];
int n,m,k,T,f;
int dir[4][2]={0,1,0,-1,1,0,-1,0};
struct node
{
    int x,y,t,v;
    node(){}
    node(int x,int y,int v,int t):x(x),y(y),v(v),t(t){}
};
queue<node>qu;
void bfs(int x,int y)
{
    qu.push(node(x,y,0,0));
    vis[x][y][0]=1;
    while(!qu.empty()){
        node temp=qu.front();qu.pop();
        
        int x=temp.x,y=temp.y,t=temp.t,v=temp.v;
        if(v==k){
            printf("%d\n",t);
            f=1;
            return;
        }
        for(int i=0;i<4;i++){
            int xx=x+dir[i][0],yy=y+dir[i][1],tt=t+1,vv=v;
            if(xx>=1&&xx<=n&&yy>=1&&yy<=m&&s[xx][yy]!='#'){
                if(s[xx][yy]>='1'&&s[xx][yy]<='9'
                    Etc.) {=vv+s[xx][yy]-'0';
                }
                if(vis[xx][yy][vv]==0&&vv<=k){
                    vis[xx][yy][vv]=1;
                    qu.push(node(xx,yy,vv,tt));
                }
            }
        }
    }
}
int main()
{
    scanf("%d",&T);
    while(T--){
        f=0;
        scanf("%d%d",&n,&m);
        n++,m++;
        while(!qu.empty()) qu.pop();
        for(int i=1;i<=n;i++) scanf("%s",s[i]+1);
        scanf("%d",&k);
        for(int i=1;i<=n;i++){
            for(int j=0;j<=m;j++){
                for(int a=0;a<=k;a++) vis[i][j][a]=0;
            }
        }
        int x,y;
        for(int i=1;i<=n;i++){
            for(int j=1;j<=m;j++){
                if(s[i][j]=='*') x=i,y=j;
            }
        }
        bfs(x,y);
        if(f==0) printf("-1\n");
    }
    return 0;
}

 

Guess you like

Origin www.cnblogs.com/ww123/p/11652662.html