算法竞赛入门经典(第2版)习题3-5 谜题(Puzzle) Uva227

来源:互联网 发布:java web 日志 编辑:程序博客网 时间:2024/06/07 02:03

C++编写

#include<iostream>using namespace std;int main(){    int x = 2, y = 1;    char Puzzle[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'},    };    char cons;    char temp;    while (cin >> cons&&cons != '0')    {        if (x < 5 && y < 5)        {            if (cons == 'A' || cons == 'B' || cons == 'L' || cons == 'R')            {                if (cons == 'A')                {                    temp = Puzzle[x][y];                    Puzzle[x][y] = Puzzle[x-1][y];                    Puzzle[x-1][y] = temp;                    x--;//x,y坐标置为空格的位置                }                if (cons == 'B')                {                    temp = Puzzle[x][y];                    Puzzle[x][y] = Puzzle[x+1][y];                    Puzzle[x+1][y] = temp;                    x++;                }                if (cons == 'L')                {                    temp = Puzzle[x][y];                    Puzzle[x][y] = Puzzle[x][y-1];                    Puzzle[x][y-1] = temp;                    y--;                }                if (cons == 'R')                {                    temp = Puzzle[x][y];                    Puzzle[x][y] = Puzzle[x][y+1];                    Puzzle[x][y+1] = temp;                    y++;                }            }            else                cout << "Please enter A,B,L,R!\n";        }        else            cout << "This operation cannot be performed.\n";    }    for (int i = 0; i < 5; i++)    {        for (int j = 0; j < 5; j++)            cout << Puzzle[i][j] << ' ';        cout << endl;    }    return 0;}
1 0
原创粉丝点击