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

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