UVA227 puzzle

题目:给你一个字母组成的矩阵,其中有一个空位,给你移动的规则(类似平面的一种拼图游戏);

            问是否操作合法,合法时输出移动后的结果

#include<stdio.h>

char pic[5][5] = {
		{'T','R','G','S','J'},
		{'X','D','O','K','I'},
		{'M',' ','V','L','N'},
		{'W','P','A','B','E'},
		{'U','Q','H','C','F'}
	};
int now[2] = {2,1};
bool change(char c) {
	int y = now[0];
	int x = now[1];
	switch(c) {
		case 'A': {		//y-1 -> y
			if(pic[y-1][x]) {
				pic[y][x] = pic[y-1][x];
				pic[y-1][x] = ' ';
				now[0] = y-1;
				return true;
			}
			return false;
		}
		case 'B': {		//y+1 -> y
			if(pic[y+1][x]) {
				pic[y][x] = pic[y+1][x];
				pic[y+1][x] = ' ';
				now[0] = y+1;
				return true;
			}
			return false;
		}
		case 'L': {		//x-1 -> x
			if(pic[y][x-1]) {
				pic[y][x] = pic[y][x-1];
				pic[y][x-1] = ' ';
				now[1] = x-1;
				return true;
			}
			return false;
		}
		case 'R': {		//x+1 -> x
			if(pic[y][x+1]) {
				pic[y][x] = pic[y][x+1];
				pic[y][x+1] = ' ';
				now[1] = x+1;
				return true;
			}
			return false;
		}
	}
}

int main(void) {
	char c;
	for(int i=0;i<5;i++) {
		for(int j=0;j<5;j++) {
			printf(" %c ",pic[i][j]);
		}
		printf("\n");
	}
	while(scanf("%c",&c)!=EOF) {
		if(!change(c)) {
			printf("This puzzle has no final configuration\n");
			break;
		}
		for(int i=0;i<5;i++) {
			for(int j=0;j<5;j++) {
				printf(" %c ",pic[i][j]);
			}
			printf("\n");
		}
	}
}
点赞