[Algorithms] – Thám hiểm

Solution:

#include <iostream>
#include <stdio.h>
#include <math.h>
using namespace std;
void East(int &x, int &y, int &ex, int &ey)
{
 ex = x, ey = y, x++;
}
void West(int &x, int &y, int &ex, int &ey)
{
 ex = x, ey = y, x--;
}
void North(int &x, int &y, int &ex, int &ey)
{
 ex = x, ey = y, y++;
}
void South(int &x, int &y, int &ex, int &ey)
{
 ex = x, ey = y, y--;
}
void Right(int &x, int &y, int &ex, int &ey)
{
 switch (x - ex)
 {
 case 1: South(x, y, ex, ey); break;
 case -1: North(x, y, ex, ey); break;
 case 0:
 switch (y - ey)
 {
 case 1: East(x, y, ex, ey); break;
 case -1: West(x, y, ex, ey); break;
 }; break;
 }
}
void Left(int &x, int &y, int &ex, int &ey)
{
 switch (x - ex)
 {
 case 1: North(x, y, ex, ey); break;
 case -1: South(x, y, ex, ey); break;
 case 0:
 switch (y - ey)
 {
 case 1: West(x, y, ex, ey); break;
 case -1: East(x, y, ex, ey); break;
 }; break;
 }
}
void Continue(int &x, int &y, int &ex, int &ey)
{
 switch (x - ex)
 {
 case 1: East(x, y, ex, ey); break;
 case -1: West(x, y, ex, ey); break;
 case 0:
 switch (y - ey)
 {
 case 1: North(x, y, ex, ey); break;
 case -1: South(x, y, ex, ey); break;
 }; break;
 }
}
void Back(int &x, int &y, int &ex, int &ey)
{
 switch (x - ex)
 {
 case 1: West(x, y, ex, ey); break;
 case -1: East(x, y, ex, ey); break;
 case 0:
 switch (y - ey)
 {
 case 1: South(x, y, ex, ey); break;
 case -1: North(x, y, ex, ey); break;
 }; break;
 }
}
void xl(int &x, int &y, int &ex, int &ey, char c)
{
 switch (c)
 {
 case 'E': East(x, y, ex, ey); break;
 case 'W': West(x, y, ex, ey); break;
 case 'N': North(x, y, ex, ey); break;
 case 'S': South(x, y, ex, ey); break;
 case 'L': Left(x, y, ex, ey); break;
 case 'R': Right(x, y, ex, ey); break;
 case 'C':Continue(x, y, ex, ey); break;
 case 'B': Back(x, y, ex, ey); break;
 }
}
double tinhkhoangcach(char *A, int n)
{
 int x = 0, y = 0, ex = 0, ey = 0;
 for (int i = 0; i<n; i++)
 {
 xl(x, y, ex, ey, A[i]);
 }
 return sqrt((double)(x*x + y*y));
}
int main()
{
 char A[] = { 'W', 'R', 'E', 'C', 'S', 'S', 'C', 'R', 'W', 'W', 'C', 'R', 'N' }; 
 int n = 13;
 double kq = tinhkhoangcach(A, n);
 // cout << kq;
 printf("%.1lf", kq);
}
Advertisements

One thought on “[Algorithms] – Thám hiểm

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s