UVA439-水题

题意:一只棋盘上的马,从一个点到另外一个点要走多少步

解法:广搜

#include<stdio.h>
#include<iostream>
#include <strstream>
#include<string>
#include<memory.h>
#include<math.h>
#include<sstream>
using namespace std;
const int MAXR = 8;
const int MAXC = 'h' - 'a' + 1;
struct Node
{
	int r;
	int c;
	int total;
};
const Node dir[] = { { -1, 2 }, { 1, 2 }, { -2, 1 }, { 2, 1 }, { -2, -1 }, { 2,
		-1 }, { -1, -2 }, { 1, -2 } };
struct Queue
{
	Node a[MAXR * MAXC];
	int total;
	int position;
	Queue()
	{
		total = 0;
		position = 0;
	}
	;
	Node offerNode()
	{
		Node node = a[position++];
		return node;
	}
	void pushNode(Node node)
	{
		a[total++] = node;
	}
	bool empty()
	{
		return position == total;
	}
};
int bfs(Queue queue, Node e, int used[][MAXC + 1])
{
	Node t;
	while (!queue.empty())
	{
		t = queue.offerNode();
		if (t.c == e.c && t.r == e.r)
		{
			return t.total;
		}
		int nt = t.total + 1;
		for (int i = 0; i < 8; i++)
		{
			int er = t.r + dir[i].r;
			int ec = t.c + dir[i].c;
			if (er < 1 || ec < 1 || er > MAXR || ec > MAXC || used[er][ec] == 1)
			{
				continue;
			}
			Node node;
			node.c = ec;
			node.r = er;
			node.total = nt;
			queue.pushNode(node);
			used[er][ec] = 1;
		}
	}
	return 0;
}
int main()
{
	//freopen("d:\\1.txt", "r", stdin);
	char sc, sr;
	char ec, er;
	while (cin >> sc >> sr >> ec >> er)
	{
		int total = 0;
		if (sc == ec && sr == er)
		{
			cout << "To get from " << sc << sr << " to " << ec << er
					<< " takes " << total << " knight moves." << endl;
			continue;
		}
		Queue queue;
		Node s, e;
		s.r = sr - '0';
		s.c = sc - 'a' + 1;
		e.r = er - '0';
		e.c = ec - 'a' + 1;
		s.total = 0;
		queue.pushNode(s);
		int used[MAXR + 1][MAXC + 1];
		memset(used, 0, sizeof(used));
		used[s.r][s.c] = 1;
		total = bfs(queue, e, used);
		cout << "To get from " << sc << sr << " to " << ec << er << " takes "
				<< total << " knight moves." << endl;
	}
}

  

posted on 2017-05-12 14:46 好吧,就是菜菜 阅读( ...) 评论( ...) 编辑 收藏

转载于:https://www.cnblogs.com/shuiyonglewodezzzzz/p/6845526.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值