LintCode 941 在一块大小为 2x3 的板上,有 5 块瓦片,分别用整数 1 到 5 表示,还有一块空地用 0 表示。

BFS求最小步数

class Solution {
public:
    /**
     * @param board: the given board
     * @return:  the least number of moves required so that the state of the board is solved
     */
    string vector2string(vector<vector<int>> v) {
        string res(6, '0');
        int j = 0;
        for (int i = 0; i < 2; i++) {
		    for (int k = 0; k < 3; k++) {
			    res[j] = v[i][k] + '0';
			    j++;
		    }
	    }
	    return res;
    }

    vector<vector<int>> string2vector(string tar){
        vector<vector<int>> v(2, vector<int>(3,0));
	    int j = 0;
	    for (int i = 0; i < 2; i++) {
		    for (int k = 0; k < 3; k++) {
			    v[i][k] = tar[j] - '0';
			    j++;
		    }
	    }
	    return v;
    }

    int slidingPuzzle(vector<vector<int>> &board) {
        // write your code here
        string target = "123450" , cur = vector2string(board);
        vector<vector<int>> move = {{1,0},{0,1},{0,-1},{-1,0}};
        unordered_set<string> s;
        s.insert(cur);
        queue<string> q;
        q.push(cur);
        int res = 0;
        while (!q.empty()) {
            res++;
            int n = q.size();
            while (n > 0) {
                string temp = q.front();
                q.pop();
                if (temp == target)
                    return res-1;
                vector<vector<int>> v = string2vector(temp);
                int pos_x, pos_y;
                for (int i = 0; i < 2; i++) {
                    for (int j = 0; j < 3; j++) {
                        if (v[i][j] == 0) {
                            pos_x = i;
                            pos_y = j;
                            break;
                        }
                    }
                }
                for (int i = 0; i < 4; i++){
                    int new_pos_x = pos_x + move[i][0],
                        new_pos_y = pos_y + move[i][1];
                    if (new_pos_x >= 0 && new_pos_x <=1 && new_pos_y >= 0 && new_pos_y <= 2) {
                        vector<vector<int>> new_v = v;
                        swap(new_v[pos_x][pos_y], new_v[new_pos_x][new_pos_y]);
                        string str = vector2string(new_v);
                        if (s.count(str) == 0) {
                            q.push(str);
                            s.insert(str);
                        }
                    }
                }
                n--;

            }
        }
        return -1;
    }
};

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值