sicily 1444 Prime Path bfs

        bfs, 这题WA了好几次,百思不得其解,后来发现判断状态是否合法是想错了,误认为一定要在给定两个数范围内,其实只要是4位数就可以

#include <iostream>

#include <queue>

#include <cstring>

#include <memory.h>

#include <stdlib.h>

using namespace std;



struct state

{

	char num[5];

	int pounds;

	state(char num[]) {strcpy(this->num, num); pounds = 0;}

	state() {pounds = 0;}

};

bool isvisit[10][10][10][10];

bool isPrime[10005]; //素数表

char start[5], goal[5];



void bfs();

void makePrime();



int main()

{

	int n;

	makePrime();

	cin >> n;

	

	for (int i = 0; i < n; i++)

	{

		cin >> start >> goal;		

		bfs();

	}

	return 0;

}



void bfs()

{

	memset(isvisit, false, sizeof(isvisit));



	queue<state> Q;

	Q.push(state(start));

	int result;

	state tmp, hold;

	while (!Q.empty())

	{

		tmp = Q.front();

		Q.pop();



		if (strcmp(tmp.num, goal) == 0)

		{

			cout << tmp.pounds << endl;

			return;

		}



		for (int i = 0; i < 4; i++)

			for (int j = 0; j < 10; j++)

			{

				strcpy(hold.num, tmp.num);

				hold.num[i] = j+'0';

				hold.pounds = tmp.pounds + 1;

				result = atoi(hold.num);



				//注意,result可以不在[start, goal]范围内!

				if ( result > 1000 && result <= 9999 &&

					 isPrime[result]   &&

					!isvisit[hold.num[0]-'0'][hold.num[1]-'0'][hold.num[2]-'0'][hold.num[3]-'0'])

				{

					isvisit[hold.num[0]-'0'][hold.num[1]-'0'][hold.num[2]-'0'][hold.num[3]-'0'] = true;

					Q.push(hold);

				}

			}

	}

	cout << "Impossible" << endl;

}



//筛选法求1~10000之间素数

void makePrime()

{

	int i, j;

	memset(isPrime, true, sizeof(isPrime));

	isPrime[0] = false;

	isPrime[1] = false;



	for (i = 2; i*i < 10000; i++)

	{

		if (isPrime[i])

		{

			for (j = 2; j*i < 10000; j++)

				isPrime[j*i] = false;

		}

	}

}

你可能感兴趣的:(Path)