算法竞赛入门经典(紫书)第三章——Puzzle UVA-227

题意:
可以理解为有一个 5×5 5 × 5 的拼图,里面有 24 个字母和一个空格。
假定 ‘A’ 代表着空格上移,’B’ 代表着空格下移,’R’ 代表着空格右移,’L’ 代表着空格左移。
要求针对给出的移动操作输出移动后的图或判断移动是否合法。

Input:
1. 前五行是拼图,接下来是移动操作,直到以 0 结尾才结束。
2. 会有多个连续数据,以单个 Z 字母结束输入。

Output:
1. 每次输出要打印出数据编号,比如 Puzzle #1
2. 移动操作合法则输出拼图,不合法则输出指定语句:This puzzle has no final config.

思路:
基本的思路是模拟。读入 5×5 5 × 5 的图和移动操作,然后移动,移动过程中判断操作是否合法。
需要注意的几点是:
1. 读入拼图时因为有空格的存在,所以用 gets() 函数来的方便。
2. 数据输入以 Z 字母结尾,这边要进行判断。
3. 读入移动操作时要判断末尾字符是不是数字 0 来决定是否需要结束读入。
4. 移动操作非法的情况是
(1) 空格在第一行时向上移动
(2) 空格在第四行时向下移动
(3) 空格在第一列时向左移动
(4) 空格在第四列时向右移动

代码:

#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
using namespace std;
typedef long long LL;

char puz[5][10];
char mov[200];
int x, y;

bool Input()
{
    for(int i=0; i<5; i++){
        if(gets(puz[i]) == NULL){
            return false;
        }
    }
    //找空格位置
    x = 0; y = 0;
    for(int i=0; i<5; i++){
        bool ok = false;
        for(int j=0; j<5; j++){
            if(puz[i][j] == ' '){
                x = i; y = j;
                ok = true; break;
            }
        }
        if(ok) break;
    }

    strcpy(mov, "");
    char tmp[100];
    while(true){
        gets(tmp);
        int len = strlen(tmp);
        strcat(mov, tmp);
        if(tmp[len-1] == '0') break;
    }
    return true;
}

void print()
{
    for(int i=0; i<5; i++){
        for(int j=0; j<5; j++){
            printf("%c%c", puz[i][j], j==4?'\n':' ');
        }
    }
}

int main()
{
    //freopen("in.txt", "r", stdin);
    int t = 1;
    while(Input()){
        //移动
        bool ok = true;
        int len = strlen(mov);
        for(int i=0; i1; i++){
            if(mov[i] == 'A'){  //空格上移
                if(x == 0){
                    ok = false; break;
                }
                puz[x][y] = puz[x-1][y];
                puz[x-1][y] = ' ';
                x--;
            }else if(mov[i] == 'B'){  //空格下移
                if(x == 4){
                    ok = false; break;
                }
                puz[x][y] = puz[x+1][y];
                puz[x+1][y] = ' ';
                x++;
            }else if(mov[i] == 'R'){  //空格右移
                if(y == 4){
                    ok = false; break;
                }
                puz[x][y] = puz[x][y+1];
                puz[x][y+1] = ' ';
                y++;
            }else if(mov[i] == 'L'){  //空格左移
                if(y == 0){
                    ok = false; break;
                }
                puz[x][y] = puz[x][y-1];
                puz[x][y-1] = ' ';
                y--;
            }
        }

        if(t != 1) printf("\n");
        printf("Puzzle #%d:\n", t++);
        if(!ok){
            printf("This puzzle has no final configuration.\n");
        }else{
            print();
        }
    }
    return 0;
}

想看书上的源代码的话看这 (^▽^)
https://github.com/aoapc-book/aoapc-bac2nd

你可能感兴趣的:(acm,紫书,acm)