當前位置:首頁 > 資訊 > info6 > 正文

zju 1091

發表于: 2014-04-05   作者:chen_xinjia   來源:轉載   瀏覽:
摘要: //TravelingKnightProblem #include"stdafx.h" #include #include #include #include usingnamespacestd; inta[8][8];//棋盤 intMAP[8][2]={{2,1},{2,-1},{-2,1},{-2,-1},{1,2},{-1,2},{-1,-2},{1,-2}};//8個方向 typedef
// Traveling Knight Problem
#include "stdafx.h"
#include <string>
#include <string.h>
#include<iostream>
#include <queue>
using  namespace std;
int a[8][8];//棋盤
int MAP[8][2] = { { 2, 1 }, { 2, -1 }, { -2, 1 }, { -2, -1 }, { 1, 2 }, { -1, 2 }, { -1, -2 }, { 1, -2 } };//8個方向
typedef struct
{
	int x;
	int y;
	int moves;
} NodeStru;
NodeStru Start, End,temp;
void bfs(queue<NodeStru>knight)
{
	int x, y;
	while (!knight.empty())
	{
		temp = knight.front();
		knight.pop();
		if (temp.x == End.x&&temp.y == End.y)
			break;
		for (int i = 0; i < 8; i++)
		{
			x = temp.x + MAP[i][0];
			y = temp.y + MAP[i][1];
			if (x >= 0 && x <8 && y >= 0 && y <8 &&!a[x][y])
			{
				Start.x = x, Start.y = y;
				Start.moves = temp.moves + 1;
				knight.push(Start);
				a[x][y] = 1;//走過了
			}
		}
	}
}
int main()
{
	queue<NodeStru>knight;
	string s1, s2;
	//char s1[2], s2[2];
	 while (cin>>s1>>s2)
	{
		
		if(s1==s2)// (strcmp(s1,s2) == 0)
		{
			cout << "To get from " << s1 << " to "<<s2 << " takes 0 knight moves." << endl;
		}
		else
		{
			memset(a, 0, sizeof(a));
			Start.x = s1[0] - 'a';
			Start.y = s1[1] - 49;
			a[Start.x][Start.y] = 1;
			Start.moves = 0;
			End.x = s2[0] - 'a';
			End.y = s2[1] - 49;
			///////////////////////////////////////////////
			//入列
			knight.push(Start);
			bfs(knight);
			cout << "To get from " << s1 << " to " << s2 << " takes "<<temp.moves<<" knight moves." << endl;

		}	
		
		while (!knight.empty())
		{
			knight.pop();
		}//記得清空棧!
	}

}

基本是老師的代碼。。我就加了四句。。。但過程也是很不容易的,因為對visual studio太不熟悉了,為什么那個#include "stdafx.h"一定要加在第一句呢,還有cin>>char;
最后ctrl + z 會出現錯誤呢? 還有strcmp 為什么在string 時會出錯?

zju 1091

版權所有 IT知識庫 CopyRight ? 2009-2015 IT知識庫 IT610.com , All Rights Reserved. 京ICP備09083238號
广东25选5开奖结果