方格广搜

// 21:45
// 1、初始状态:3 * 3数组 
//         数据结构;结构体{3*3数组,0的位置},queue,map,
//                    方向数组 
// 2、过程:广度优先搜索(超时,改为双向广度优先搜索搜索量由40000多降为5000多),每次从队列中取下一个节点访问并进行扩展。每次像上下左右四个方向试探,若未访问,则加入待访问队列 
//         扩展:注意判断是否越界 
//        访问标记:map容器来记录走过的标记(相当于一维中的vis[])
// 3、结束:队列为空结束 

#include <iostream>
#include <queue>
#include <map>
#include <string>
#include <cstring>
#include <conio.h>
using namespace std;

struct Node {
    string g;
    int i, j;
    int type;
    int ans;
};

int dir[4][2] = {
    {-1, 0}, {1, 0},
    {0, -1}, {0, 1}
};

queue<Node> q;
map<string, int> mp; 
int ans;

Node MakeNode(string s, int type) 
{
    Node node;
    for (int i = 0; i < s.size(); i++)
        if (s[i] == '.') {
            node.i = i / 3; node.j = i % 3;
        }
    node.g = s;
    node.type = type;
    if (node.type == 1)
        node.ans = 1;
    else 
        node.ans = -1;
 
    return node;
}

bool bfs(Node node1, Node node2) 
{
    // 初始化
    ans = 0;
    while (!q.empty()) q.pop();
    q.push(node1); q.push(node2);
        
    while (!q.empty()) {
        Node node = q.front(); q.pop();
        for (int i = 0; i < 4; i++) {
            Node tmp = node;
            tmp.i += dir[i][0];
            tmp.j += dir[i][1];
            if (tmp.i < 0 || tmp.i >= 3) continue;    // 1.竟然忘了判断是否越界 
            if (tmp.j < 0 || tmp.j >= 3) continue;
            tmp.g[node.i * 3 + node.j] = tmp.g[tmp.i * 3 + tmp.j];
            tmp.g[tmp.i * 3 + tmp.j] = '.';
            // 正走步数为正,反走步数为负 
            if (node.type == 1) {
                tmp.type = 1;
                tmp.ans += 1;
            } else {
                tmp.type = 2;
                tmp.ans -= 1;
            }                        
                            
            if (mp.find(tmp.g) != mp.end()) {
                int x = mp[tmp.g];
                if (tmp.type == 1 && x < 0) {    // 2.注意边界是x <= 0 而非x < 0
                    ans = tmp.ans + (-1) * x - 2;
                    return true;
                }     
                    
                else if (tmp.type == 2 && x > 0) { 
                    ans = (-1) * tmp.ans + x - 2;
                    return true; 
                } 
                // return true;    // 3.仅仅是return true;放在了外面让我非常郁闷地调了两小时 
            } else { 
                mp[tmp.g] = tmp.ans;    
                q.push(tmp);
            }
        }
    }
    return false;
}

int main()
{
    string s1, s2;
    while (cin >> s1 >> s2) {
        if (s1 == s2) cout << 0 << endl;
        
        mp.clear();
        mp[s1] = 1;
        mp[s2] = -1;
        Node node1 = MakeNode(s1, 1); 
        Node node2 = MakeNode(s2, 2);
        
        if (bfs(node1, node2) == true) 
            cout << ans << endl;
        else 
            cout << -1 << endl;
    }
    return 0;
}

 

posted on 2014-03-21 23:55  Gddxz  阅读(172)  评论(0编辑  收藏  举报

导航