UVa 10274:fans and Gems, God Cow Rujia Liu's question (iii)

Source: Internet
Author: User
Tags bool empty hash printf touch

Topic Link:

Uva:http://uva.onlinejudge.org/index.php?option=com_onlinejudge&itemid=8&category=24&page=show_ problem&problem=1215

zoj:http://acm.zju.edu.cn/onlinejudge/showproblem.do?problemcode=1237

Type: Implicit graph Search + nausea simulation + hash weight +bfs+dfs

Original title:

Tomy ' s fond of a game called ' Fans and Gems ' (also known as Gravnic). In the game, he can use fans to collect gems, but him satisfied with his play only if all the gems are and min iMAL number of steps. The game is played as following:

There are three kinds of gems, one colored red, one colored green and one colored blue. There are walls in the spaces, as you. There are also virtual fans everywhere in the game, but to cannot you. What the fans should blow to which for you can does each time are to select a DIRECTION. There are only four directions possible:up. Then, the fans would work, pushing all the gems to fly to the selected direction in the same speed, until they cannot move Further (blocked by the wall, other gems or a flyer). Then, if there are some gems touching some same-colored gem (touching means adjacent in one of the four directions), they D Isappear simultaneously. This is the fans are still working, so some gems could go on moving and direction after some gems. The fans stop working when all the gems cannot, and none of the them should disappear. There May is some flyers that can is moved by the fans, but they can NEVER disappear.

You are are to write a program that finds the minimal number of operations to make all the gems disappear.

Input

The input file begins with a integer T, indicating the number of test cases. (1<=T<=50) Each test case begins with two integers N, M, indicating the height and width of the map. (1<=N<=12,1<=M<=20) In the following N lines, each line contains M characters describing the map. There is one line over each map, ignore them. Spaces denotes empty square, ' # ' denotes a wall, ' 1 ' denotes a red gem, ' 2 ' denotes a green gem, ' 3 ' denotes a blue gem, a nd ' @ ' denotes a flyer. It's guaranteed that's the four sides of the map are all walls. The There is at least one gem in the map, and no two same-colored gems'll touch each other at the beginning of the game.

Output

You are should print a single to each case. If There is a solution, write the shortest operation sequence in a string. The ith character must is from the set {' U ', ' D ', ' L ', ' R '}, describing ith operation. The four characters represent up, DOWM, left and right respectively. If there are more than one solution, choose the lexicographical smallest one, if there are no solution, output-1 on the L Ine. When a solution exists, your need only or fewer steps to carry it out.

Sample Input

2
9 8
########
# # 1##
# # 2 #
# 1 # #
# #2 # #
# 1@##
###   ##
#### ###
########

7 8
########
#212121 #
#      #
# # # ##
# #    #
#     ##
########

Sample Output

LURD
Dl

The main effect of the topic:

Tomy like a game called fans and gems (fans and Gems, the first word does not know how to translate), players can let fans to collect gems. Tomy hopes to collect all the gems with a minimum number of steps. The way the game is played:

There are three kinds of gems: red, green, blue, respectively, with 1,2,3 to replace, the map is surrounded by walls, the map may also have aircraft, with @ instead. Fans are virtual, invisible, and they are everywhere in every corner of the map. You can choose a direction each time (above, down, left, right), and then the fans will push all the gems and craft on the map in this direction (in fact, choose a direction, and then all the gems and aircraft in the map will move in that direction at the same speed). The stones and the craft will stop when they touch the wall. Or a gem or craft that has ceased to come to an end. In the process of moving, once the same gem is found to be adjacent, then the adjacent same gems will disappear.

Analysis and Summary:

The topic is very interesting, but ... This problem involves a simulation process that increases the level of nausea in the previous question to a number of levels ...

You need to simulate the movement of gems and aircraft throughout the map, and then eliminate the same gems that are adjacent to each other.

Simulation of the process is good, but also a big step towards AC.

Then it's like doing a general implicit graph Search + hash weight.

There is also a need to note that if there are a variety of scenarios, then output the smallest dictionary order, so only need to search, the direction in the dictionary order d,l,r, u in order to search.

WA Once, Reason:

1. More than 18 steps are no longer considered.

2. After each input will be more than one line of useless, and not necessarily empty line (this is still read the discuss to the input and output to know), to read out this line.

* * UVa 10274-fans and Gems * Implicit graph Search + BFS + analog + hash Weight * time:0.376s (UVa) 590ms (zoj) * Author:d_doub  
Le/* #include <iostream> #include <cstring> #include <cstdio> using namespace std;  
typedef char STATE[13][21];  
State map;  
int dir[4][2]={{1,0},{-1,0},{0,1},{0,-1}};  
Char dir_name[] = {' D ', ' L ', ' R ', ' U '};  
      
      
int n,m;  
      
inline void swap (char &ch1, char &ch2) {char t=ch1; ch1=ch2; ch2=t;} inline bool Is_gem_fly (char ch) {if (ch== ' 1 ') | | ch== ' 2 ' | | ch== ' 3 ' | |  
    ch== ' @ ') return true;  
return false; //Simulate direction move process, note in dictionary order: D,l,r,u//This article url:http://www.bianceng.cn/programming/sjjg/201410/45633.htm inline bool mo  
    ve (state &s, int dir) {bool flag=false;  
                if (dir==0) {//Next for (int i=1; i<m-1; ++i) {for (int j=n-1; j>0;--j) if (s[j][i]== ") {  
                int k = j-1;  
                while (s[k][i]== ')--k;  
  if (Is_gem_fly (S[k][i])) {                  Swap (S[j][i], s[k][i]);  
                Flag=true;  
            else j=k; } else if (dir==1) {//left for (int i=1; i<n-1; ++i) {for (int j=1; j<m -1;  
                ++J) if (s[i][j]== ') {int k = j+1;  
                while (s[i][k]== ') ++k;  
                if (Is_gem_fly (S[i][k])) {swap (s[i][j], s[i][k]); flag=true;  
            else j=k; }} else if (dir==2) {//right for (int i=1; i<n-1; ++i) {for (int j=m-1; j&gt ; 1;  
                --J) if (s[i][j]== ') {int k = j-1;  
                while (s[i][k]== ')--k;  
                if (Is_gem_fly (S[i][k])) {swap (s[i][j], s[i][k]); flag=true;  
            else j=k;  
     }} else if (dir==3) {//Up   for (int i=1; i<m-1; ++i) {for (int j=1; j<n-1; ++j) if (s[j][i]== ') {int k = j+1;  
                while (s[k][i]== ') ++k;  
                if (Is_gem_fly (S[k][i])) {swap (S[j][i], s[k][i]); flag=true;  
            else j=k;  
    }} if (flag) return true;  
return false;  
    } void Dfs (state &s, char ch, int x, int y) {//Eliminate the same gem s[x][y] = ';  
        for (int i=0; i<4; ++i) {int dx=x+dir[i][0], dy=y+dir[i][1];  
    if (s[dx][dy]==ch) DFS (s, ch, dx, dy);  
    } inline bool Remove (state &s) {bool Ok=false;  
            for (int i=1; i<n-1; ++i) {for (int j=1; j<m-1; ++j) if (Is_gem_fly (s[i][j)) && s[i][j]!= ' @ ') {  
            BOOL Flag=false;  
                for (int k=0; k<4; ++k) {int dx=i+dir[k][0], dy=j+dir[k][1]; if (dx>=0 && dx<n && dy>=0 && dy<m && S[i][j]==s[dx][dy]) {flag=true   
                    ;  
                Break   
                } if (flag) {OK = true;  
            DFS (S,S[I][J],I,J);  
    }} if (OK) return true;  
return false;  
    inline void run (state &s, int dir) {//in which direction the step while (move (S, dir)) {remove (s);  
} const int MAXN = 100000;  
const int hashsize = 1000003;  
State QUE[MAXN];  
int head[hashsize], NEXT[MAXN], FATHER[MAXN], Step[maxn], ans;  
      
Char PATH[MAXN];  
    inline void init_lookup_table () {ans =-1;   
    father[0]=0;  
    Step[0] = 0;   
    memset (head, 0, sizeof);  
memset (que, 0, sizeof (que));  
    } inline int hash (state &s) {int seed=131, v=0; for (int i=0; i<n; ++i) {for (int j=0; j<m; ++j) v = (v*seed+s[i][j));  
    0x7fffffff;  
return v%hashsize;  
    BOOL Try_to_insert (int s) {int h = hash (que[s]);  
    int u = head[h];  
        while (U) {if (memcmp (Que[u], que[s], sizeof (que[s)) ==0) return false;  
    U = next[u];  
    } Next[s] = Head[h];  
    HEAD[H] = s;  
return true;  
            } inline bool Is_ok (state &s) {for (int i=1; i<n-1; ++i) {for (int j=1; j<m-1; ++j) if (s[i][j]== ' 1 ' | | s[i][j]== ' 2 ' | |  
    s[i][j]== ' 3 ') return false;  
return true;  
    BOOL BFs () {init_lookup_table ();  
    int front=0, rear=1;  
    memcpy (Que[0], map, sizeof (map));  
      
    Try_to_insert (0);  
        while (front < rear) {state &s = Que[front];  
        if (Step[front] >) {++front; continue;  
            } if (IS_OK (s)) {ans = front;  
        return true;  
      for (int i=0; i<4; ++i) {state &t = que[rear];      memcpy (t, S, sizeof (s));  
            Run (t, I);  
                if (Try_to_insert (rear)) {Step[rear] = step[front]+1;  
                Father[rear] = front;  
                Path[rear] = Dir_name[i];  
            ++rear;  
    }} ++front;  
return false;  
        } void Print_path (int cur) {if (cur) {Print_path (father[cur));  
    printf ("%c", Path[cur]);  
    int main () {int T;  
    Char str[1000];  
    scanf ("%d%*c", &t);  
        while (t--) {scanf ("%d%d%*c", &n,&m);   
        for (int i=0; i<n; ++i) gets (map[i));  
        Gets (str);  
        if (!BFS ()) printf (" -1\n");  
            Else{Print_path (ans);  
        printf ("\ n");  
} return 0; }

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.