I have to develop a C program for a given set of input values, where we describe the rectanged figure by its boundary by specifying a starting point and a series of movements in four basic directions – as if we were going around the formation along its boundary.
We enter each movement in the direction (WESN) and length – "W 3" means moving from the current position three steps west (left).
The figure in Figure 1 could be described — starting from the upper-right corner — as:
"W 6, S 2, W 3, S 2, E 1, S 2, E 2, N 1, E 2, N 1, E 2, N 1, W 2, N 1, E 3, S 3, E 1, N 5".
My problem is:
Thanks.
The shape is called polyomino. It's special case of polygon.
The problem of finding the area can be solved by starting at point (0,0)
with a polygon of area 0
. Next, extending the area by rectangle while moving horizontally.
Assume that the current point is (x,y)
. Moving to east by d
unit means adding a rectangle at points (x,0) -> (x,y) -> (x + d, y) -> (x + d, 0)
. Rectangle's area is d * y
.
When moving west one needs to subtract the rectangle.
The final area is positive if the walk is clockwise or negative if the path was counter-clockwise.
This approach results in a very simple program:
#include <stdio.h>
int main() {
int x = 0, y = 0, A = 0, d;
int c;
while ((c = getchar()) != EOF) {
if (c == 'W' && scanf(" %d", &d) == 1) {
x += d;
A += d * y;
} else if (c == 'E' && scanf(" %d", &d) == 1) {
x -= d;
A -= d * y;
} else if (c == 'N' && scanf(" %d", &d) == 1) {
y += d;
} else if (c == 'S' && scanf(" %d", &d) == 1) {
y -= d;
}
}
if (A < 0) A = -A;
printf("%d\n", A);
return 0;
}
For input from the question is gives the expected answer of 33
.