hdu1195 Open the Lock 广搜BFS 四维数组标记

Open the Lock

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 5732    Accepted Submission(s): 2540


Problem Description
Now an emergent task for you is to open a password lock. The password is consisted of four digits. Each digit is numbered from 1 to 9. 
Each time, you can add or minus 1 to any digit. When add 1 to '9', the digit will change to be '1' and when minus 1 to '1', the digit will change to be '9'. You can also exchange the digit with its neighbor. Each action will take one step.

Now your task is to use minimal steps to open the lock.

Note: The leftmost digit is not the neighbor of the rightmost digit.
 

Input
The input file begins with an integer T, indicating the number of test cases. 

Each test case begins with a four digit N, indicating the initial state of the password lock. Then followed a line with anotther four dight M, indicating the password which can open the lock. There is one blank line after each test case.
 

Output
For each test case, print the minimal steps in one line.
 

Sample Input
   
   
   
   
2 1234 2144 1111 9999
 

Sample Output
   
   
   
   
2 4



#include <iostream>  
#include <cstdio>  
#include <cstring>  
#include <queue>  

using namespace std;

struct node {
	int num[4], step;
};

node first, last;

//四维数组标记
bool vis[10][10][10][10];

void bfs() {
	memset(vis, false, sizeof(vis));
	queue<node> Q;
	node p, q; //用p表示当前的,q是下一步的
	p = first;
	p.step = 0;
	vis[p.num[0]][p.num[1]][p.num[2]][p.num[3]] = true;
	Q.push(p);

	while (!Q.empty()) {
		p = Q.front(); Q.pop();
		bool flag = true;
		for (int i = 0; i < 4; i++) {
			if (last.num[i] != p.num[i]) {
				flag = false;
				break;
			}
		}
		if (flag) {
			printf("%d\n", p.step);
			return;
		}

		//三种平行情况,注意一步之内任何一个元素都可能+-1,任何两个相邻元素之间都可能交换
		//+1
		for (int i = 0; i < 4; i++) {
			q = p;
			if (p.num[i] == 9) q.num[i] = 1;
			else q.num[i] = p.num[i] + 1;
			if (!vis[q.num[0]][q.num[1]][q.num[2]][q.num[3]]) {
				vis[q.num[0]][q.num[1]][q.num[2]][q.num[3]] = true;
				q.step = p.step + 1;
				Q.push(q);
			}
		}

		//-1
		for (int i = 0; i < 4; i++) {
			q = p;
			if (p.num[i] == 1) q.num[i] = 9;
			else q.num[i] = p.num[i] - 1;
			if (!vis[q.num[0]][q.num[1]][q.num[2]][q.num[3]]) {
				vis[q.num[0]][q.num[1]][q.num[2]][q.num[3]] = true;
				q.step = p.step + 1;
				Q.push(q);
			}
		}

		//exchange
		for (int i = 0; i < 3; i++) {
			q = p;
			q.num[i] = p.num[i + 1];
			q.num[i + 1] = p.num[i];
			if (!vis[q.num[0]][q.num[1]][q.num[2]][q.num[3]]) {
				vis[q.num[0]][q.num[1]][q.num[2]][q.num[3]] = true;
				q.step = p.step + 1;
				Q.push(q);
			}
		}
	}
}

int main()
{
	int T;
	char cf[10], cl[10];
	scanf("%d", &T);
	while (T--) {
		scanf("%s%s", cf, cl);
		for (int i = 0; i < 4; i++) {
			first.num[i] = cf[i] - '0';
			last.num[i] = cl[i] - '0';
		}
		bfs();
	}
	return 0;
}




你可能感兴趣的:(枚举,搜索,bfs,hduoj)