codeup【宽搜入门】8数码难题——BFS

初始状态的步数就算1,哈哈

输入:第一个3*3的矩阵是原始状态,第二个3*3的矩阵是目标状态。
输出:移动所用最少的步数

Input

2 8 3
1 6 4
7 0 5
1 2 3
8 0 4
7 6 5

Output

6

注意:题目中 0的位置是可以移动的空格。

分析:首先题目要求求最少的步数,很容易想到使用BFS ;

那么对于BFS,我们要解决的主要问题是要确定每一步的状态并保存给下次使用。

结合BFS模板考虑,首先每次移动的结果是每一步的状态,并且每次状态我们需要保存的信息有:矩阵的排序,空格的位置以及步数,所以以此为依据设计结构体;

注意到,如果要设置标记数组的话,因为每次状态下是一个数组,所以是否步方便,而该题的数组是3*3的,就算是有重复计算的状态,时间也是可以接受的,所以这里没有采取标记数组,只是简单的处理,保证不往后走。


struct node{
    int x, y;
    int step;
    int M[3][3];
    int last[2];
} Node; 
int X[4] = {0, 0, 1, -1};
int Y[4] = {1, -1, 0, 0};
int matrix[3][3], final[3][3];

bool judge(int x, int y){
    if(x < 0 || x >= 3 || y < 0 || y >= 3)
        return false;
    return true;
}
bool same(int a[3][3]){
    for(int i = 0; i < 3; i++){
        for(int j = 0; j < 3; j++){
            if(a[i][j] != final[i][j])
                return false;
        }
    }
    return true;
}
int BFS(int x, int y) {
    queue<node> Q;
    Node.x = x, Node.y = y, Node.step = 1;
    Node.last[0] = x, Node.last[1] = y;
    for(int i = 0; i < 3; i++){
        for(int j = 0; j < 3; j++){
            Node.M[i][j] = matrix[i][j];
        }       
    }
    Q.push(Node);   
    while(!Q.empty()){
        node top = Q.front();
        Q.pop();

        for(int i = 0; i < 4; i++){
            int newX = top.x + X[i];
            int newY = top.y + Y[i];        
            if(judge(newX, newY) && (newX != top.last[0] || newY != top.last[1])){
                Node.x = newX, Node.y = newY;
                Node.step = top.step + 1;
                Node.last[0] = top.x;
                Node.last[1] = top.y;
                for(int i = 0; i < 3; i++){
                    for(int j = 0; j < 3; j++){
                        Node.M[i][j] = top.M[i][j];
                    }
                }
                int tmp;
                tmp = Node.M[newX][newY];
                Node.M[top.x][top.y] = tmp;
                Node.M[newX][newY] = 0;
                if(same(Node.M)){
                    return Node.step;   
                } 
                Q.push(Node);               
            }   
        }       
    }
    return -1;
}
int main(){
    int x, y;
    for(int i = 0; i < 3; i++){
        for(int j = 0; j < 3; j++){
            cin >> matrix[i][j];
            if(matrix[i][j] == 0){
                x = i;
                y = j;
            }
        }
    }
    for(int i = 0; i < 3; i++){
        for(int j = 0; j < 3; j++){
            cin >> final[i][j];
        }
    }
    cout << BFS(x, y) << endl;
}

参考链接

https://blog.csdn.net/ikechan/article/details/81700554

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章