问题 C: 【宽搜入门】8数码难题

【宽搜入门】8数码难题

题目描述

初始状态的步数就算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

Code

#include<iostream>
#include<queue>
using namespace std;

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;
}
/**************************************************************
    Problem: 5997
    User: 14041045
    Language: C++
    Result: 正确
    Time:4 ms
    Memory:3240 kb
****************************************************************/

尝试做了每步对矩阵修改的BFS题,还行

猜你喜欢

转载自blog.csdn.net/ikechan/article/details/81700554