• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录

  • 联系
  • 订阅
  • 管理

View Post

POJ 1915 Knight Moves bfs

        这题一般bfs都能过,尝试写了个双向bfs

        单向bfs, 450+ms, 双向300+ms

#include <iostream>
#include <queue>
#include <memory.h>
using namespace std;

struct coordinate
{
	int x, y;
	int step;
};

int dir[8][2] = {{1, 2}, {1, -2}, {-1, 2}, {-1, -2 }, {2,1}, {2, -1}, {-2, 1}, {-2, -1}};
int isvisit[301][301];
int step[301][301];
coordinate goal, start;

int board;

void bfs();

int main()
{
	int n;

	cin >> n;

	while (n--)
	{
		memset(isvisit, 0, sizeof(isvisit));
		memset(step, 0, sizeof(step));
		cin >> board;
		cin >> start.x >> start.y;
		start.step = 0;
		isvisit[start.x][start.y] = 1;
		cin >> goal.x >> goal.y;
		goal.step = 0;
		isvisit[goal.x][goal.y] = 2;
		bfs();
	}
	return 0;
}

void bfs()
{
	coordinate p, next;
	queue<coordinate> Q1;
	queue<coordinate> Q2;

	p = start;
	Q1.push(p);
	p = goal;
	Q2.push(goal);
	while (! Q1.empty())
	{
		p = Q1.front();
		Q1.pop();

		if (p.x == goal.x && p.y == goal.y)
		{
			cout << p.step << endl;
			return;
		}

		for (int i = 0; i < 8; i++)
		{
			next.x = p.x + dir[i][0];
			next.y = p.y + dir[i][1];
			next.step = p.step + 1;

			if (next.x >= 0 && next.x < board && next.y >= 0 && next.y < board)
			{
				if (isvisit[next.x][next.y] == 0)
				{
					isvisit[next.x][next.y] = 1;
					step[next.x][next.y] = next.step;
					Q1.push(next);
				}

				else if (isvisit[next.x][next.y] == 2)
				{
					cout << next.step + step[next.x][next.y] << endl;
					return;
				}
			}
		}

		p = Q2.front();
		Q2.pop();

		for (int i = 0; i < 8; i++)
		{
			next.x = p.x + dir[i][0];
			next.y = p.y + dir[i][1];
			next.step = p.step + 1;

			if (next.x >= 0 && next.x < board && next.y >= 0 && next.y < board)
			{
				if (isvisit[next.x][next.y] == 0)
				{
					isvisit[next.x][next.y] = 2;
					step[next.x][next.y] = next.step;
					Q2.push(next);
				}
				else if (isvisit[next.x][next.y] == 1)
				{
					cout << next.step + step[next.x][next.y] << endl;
					return;
				}
			}
		}
	}
}

posted on 2010-11-30 20:27  sysuwhj  阅读(402)  评论(0)    收藏  举报

刷新页面返回顶部
 
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3