50183. Lights out, again

難度:4.7/5

Second Try: 4.7/5 Used Time: 29:02 Used Time: 20:12

main.c

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
#include <stdio.h>
#include <stdlib.h>
#include "lights.h"

int n;
int len;
int arr[16] = {0};
int dx[5] = {0, 0, 0, 1, -1};
int dy[5] = {0, 1, -1, 0, 0};
Lights* l;

void swap(int* a, int* b){
int t = *a;
*a = *b;
*b = t;
}

int dfs(int arr[], int now_idx, int target_size, int arr_size){
if(now_idx == target_size){
for(int i = 0; i < now_idx; i++) flip(l, arr[i], n);
if(numOfLights(l, n) == 0){
for(int i = 0; i < now_idx; i++) printf("%d ", arr[i]);
return 1;
}
else{
for(int i = 0; i < now_idx; i++) flip(l, arr[i], n);
return 0;
}
}
else{
for(int i = now_idx; i < arr_size; i++){
swap(&arr[now_idx], &arr[i]);
int rtv = dfs(arr, now_idx + 1, target_size, arr_size);
if(rtv) return 1;
swap(&arr[now_idx], &arr[i]);
}
return 0;
}
}

int main(){
l = (Lights*)malloc(sizeof(Lights));
init(l);

scanf("%d", &n); len = n * n;
int d; while(scanf("%d", &d) != EOF) flip(l, d, n);

int arr[16];
for(int i = 0; i < len; i++) arr[i] = i;

for(int i = 1; i <= len; i++){
int rtv = dfs(arr, 0, i, len);
if(rtv) break;
}
}

lights.c

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
#include <stdio.h>
#include "lights.h"

// typedef struct _lights{
// int arr[4][4];
// int cnt_on;
// }Lights;

static int dx[5] = {0, 0, 0, 1, -1};
static int dy[5] = {0, 1, -1, 0, 0};
static int is_valid(int x, int y, int n){
return x >= 0 && y >= 0 && x < n && y < n;
}

void init(Lights *l){
for(int i = 0; i < 4; i++){
for(int j = 0; j < 4; j++){
l->arr[i][j] = 0;
}
}
l->cnt_on = 0;
}

int numOfLights(Lights *l, int n){
return l->cnt_on;
}

void flip(Lights *l, int k, int n){
int x = k / n;
int y = k % n;
for(int i = 0; i < 5; i++){
int now_x = x + dx[i], now_y = y + dy[i];
if(is_valid(now_x, now_y, n)){
if(l->arr[now_x][now_y] == 0){
l->arr[now_x][now_y] = 1;
l->cnt_on++;
}
else{
l->arr[now_x][now_y] = 0;
l->cnt_on--;
}
}
}
}

void printLights(Lights *l, int n){
for(int i = 0; i < n; i++){
for(int j = 0; j < n; j++){
printf("%d%c", l->arr[i][j], (j == n - 1) ? '\n' : ' ');
}
}
}

lights.h

1
2
3
4
5
6
7
8
9
typedef struct _lights{
int arr[4][4];
int cnt_on;
}Lights;

void init(Lights *l);
int numOfLights(Lights *l,int N);
void flip(Lights *l,int i,int N);
void printLights(Lights *l,int N);

50183. Lights out, again
https://aaronlin1229.github.io/judgegirl_50183/
Author
Akizumi
Posted on
July 17, 2023
Licensed under