BFS入门--八数码问题

题目来源:codeup BFS专题问题C

题目描述

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

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

Input

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


Output

6

思路:这道题BFS搜索的每一步就是让矩阵从一个状态变为另一个状态。所以我们用一个结构体来存储状态(当前位置的横坐标,当前位置的纵坐标,从初始状态矩阵到当前状态矩阵所变换的次数,上一个状态’0’的位置)。

#include <iostream>
#include <queue>
#include <algorithm>
using namespace std;
int matrix[3][3];
int final_matrix[3][3];
struct node
{
    int x;
    int y;
    int step;
    int last[2]; //上一次的位置坐标
    int M[3][3];
} State;
int dir[4][2] = {{0, 1}, {0, -1}, {-1, 0}, {1, 0}};

bool judge(int x, int y)
{
    if (x < 0 || x >= 3 || y < 0 || y >= 3)
    {
        return false;
    }
    return true;
}

bool same(int matrix[3][3])
{
    for (int i = 0; i < 3; i++)
    {
        for (int j = 0; j < 3; j++)
        {
            if (matrix[i][j] != final_matrix[i][j])
            {
                return false;
            }
        }
    }
    return true;
}
int BFS(int x, int y)
{
    State.x = x;
    State.y = y;
    State.step = 1;
    State.last[0] = x;
    State.last[1] = y;
    for (int i = 0; i < 3; i++)
    {
        for (int j = 0; j < 3; j++)
        {
            State.M[i][j] = matrix[i][j];
        }
    }
    queue<node> Q;
    Q.push(State);
    while (!Q.empty())
    {
        node top = Q.front();
        Q.pop();
        for (int i = 0; i < 4; i++)
        {
            int nx = top.x + dir[i][0];
            int ny = top.y + dir[i][1];
            if (judge(nx, ny) && (nx != top.last[0] || ny != top.last[1]))
            {
                State.x = nx;
                State.y = ny;
                State.step = top.step + 1;
                State.last[0] = top.x;
                State.last[1] = top.y;
                for (int i = 0; i < 3; i++)
                {
                    for (int j = 0; j < 3; j++)
                    {
                        State.M[i][j] = top.M[i][j];
                    }
                }
                swap(State.M[nx][ny], State.M[top.x][top.y]);
                if (same(State.M))
                {
                    return State.step;
                }
                Q.push(State);
            }
        }
    }
    return -1;
}
int main()
{
    int sx, sy;
    for (int i = 0; i < 3; i++)
    {
        for (int j = 0; j < 3; j++)
        {
            cin >> matrix[i][j];
            if (matrix[i][j] == 0)
            {
                sx = i;
                sy = j;
            }
        }
    }
    for (int i = 0; i < 3; i++)
    {
        for (int j = 0; j < 3; j++)
        {

            cin >> final_matrix[i][j];
        }
    }
    cout << BFS(sx, sy) << endl;
    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_39504764/article/details/89848499