summaryrefslogtreecommitdiff
path: root/2017/22.c
blob: ff73c8c5b999e5d30e213bc03b0051c4a1df1ec5 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
#include <stdio.h>
#include <stdlib.h>
#include <string.h>


static void printchart(int size,char *chart,int curx,int cury){
	for(int i=0;i<size;i++){
		for(int j=0;j<size;j++){
			if(cury==i&&curx==j)putchar('[');
			else if(cury==i&&curx==j-1)putchar(']');
			else putchar(' ');
			putchar(".W#F"[(int)chart[size*i+j]]);
		}
		if(cury==i&&curx==size-1)putchar(']');
		putchar('\n');
	}
}

static int embiggen(int *sizep,char **chartp){
	int size=*sizep;
	char *chart=*chartp;

	int newsize=2*size-1,d=(size-1)/2;
	char *newchart=calloc(newsize*newsize,1);
	for(int i=0;i<size;i++){
		memcpy(newchart+newsize*(i+d)+d,chart+size*i,size);
	}
	free(chart);
	*sizep=newsize;
	*chartp=newchart;
	return d;
}

static int virus1[4][2]={{2,3}, {0,0}, {0,1}, {0,0}};
static int virus2[4][2]={{1,3}, {2,0}, {3,1}, {0,2}};

static int simulate(int size,const char *origchart,int virus[4][2],int nsteps){
	char *chart=malloc(size*size);
	memcpy(chart,origchart,size*size);
	int curx=size/2,cury=size/2,dir=0;
	int ninf=0;
	for(int iter=0;iter<nsteps;iter++){
		if(curx<0||cury<0||curx>=size||cury>=size){
			int d=embiggen(&size,&chart);
			curx+=d; cury+=d;
		}

		int v=chart[size*cury+curx];
		dir=(dir+virus[v][1])%4;
		v=virus[v][0];
		chart[size*cury+curx]=v;
		if(v==2)ninf++;

		switch(dir){
			case 0: cury--; break;
			case 1: curx++; break;
			case 2: cury++; break;
			case 3: curx--; break;
		}
	}
	return ninf;
}

int main(void){
	freopen("22.in","r",stdin);
	char *line=NULL;
	size_t linecap=0;
	int size=getline(&line,&linecap,stdin)-1;

	char *chart=malloc(size*size);
	for(int i=0;i<size;i++)chart[i]=line[i]=='#'?2:0;
	for(int i=1;i<size;i++){
		getline(&line,&linecap,stdin);
		for(int j=0;j<size;j++)chart[size*i+j]=line[j]=='#'?2:0;
	}

	int curx=size/2,cury=size/2;
	printchart(size,chart,curx,cury);

	printf("%d\n",simulate(size,chart,virus1,10000));
	printf("%d\n",simulate(size,chart,virus2,10000000));
}