演算法競賽入門經典(第2版)習題3-5 謎題(Puzzle) Uva227
阿新 • • 發佈:2019-02-11
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;
}