Puzzle UVA - 227 谜题

题目链接 

有一个5*5的网格,其中恰好有一个格子是空的,其他格子各有一个字母。一共有4种指令:A, B, L, R,分别表示把空格上、下、左、右的相邻字母移到空格中。输入初始网格和指令序列(以数字0结束),输出指令执行完毕后的网格。如果有非法指令,应输出“This puzzle has no final configuration.”,例如,图3-5中执行ARRBBL0后,效果如图3-6所示。

Puzzle UVA - 227 谜题_第1张图片

#include 
#include 
#include 
using namespace std; 
const int N = 5;
string grid[N+2]; 
char cmd[1000];
const int dx[4] = {-1,1,0,0}, dy[4] = {0,0,-1,1};
const char *CMD= "ABLR";
int main(){
	map m;
	for(int i = 0; i < 4; i++) m[CMD[i]] = i;
	int kase = 0;
   	while( getline(cin, grid[0]) && grid[0][0] != 'Z'){
   		for(int i = 1; i < N; i++) getline(cin, grid[i]);
		int len = 0;
		while(cin>> cmd[len] && cmd[len] != '0')
			 len++;
		if(kase) cout<< "\n";
		cout<< "Puzzle #"<< ++kase<< ":\n";
		int x = 1, y = 1;
		for(int i = 0; i < N; i++){
			for(int j = 0; j < N; j++){
				if(grid[i][j] == ' '){
					x = i;
					y = j;
				}
			}
		}		
		bool ok = true;
		for(int i = 0; i < len; i++){
			int idx = m[cmd[i]];
			int nx = x+dx[ idx];
			int ny = y+dy[ idx];
			if(nx < 0 || ny < 0 || nx >= N || ny >= N){
				ok = false;
				break;
			}
			swap(grid[nx][ny], grid[x][y]);
			x = nx;
			y = ny;
		}
		if(ok){
			for(int i = 0; i < N; i++){
				for(int j = 0; j < N-1; j++)
					cout<< grid[i][j]<< " ";
				cout<< grid[i][N-1]<< "\n";
			}
		}else{
			cout<< "This puzzle has no final configuration.\n";
		}
		getline(cin,grid[0]);//还有一个换行符未读掉。
	}
    return 0;
}

 

你可能感兴趣的:(算法竞赛入门经典(第二版))