Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdlib.h>
- #include <sys/stat.h>
- #include <sys/types.h>
- #include <sys/mman.h>
- #include <fcntl.h>
- #include <string.h>
- #include <unistd.h>
- #include <inttypes.h>
- enum Direct { RIGHT, LEFT, UP, DOWN };
- int main(int argc, char * argv[]) {
- const char * path = argv[1];
- long long rows = strtol(argv[2], NULL, 10);
- long long cols = strtol(argv[3], NULL, 10);
- int fd = open(path, O_RDWR, 0); // что-то исправить
- if (fd < 0) abort();
- struct stat st;
- fstat(fd, &st);
- long long sz = rows * cols;
- if (ftruncate(fd, sz * 4) < 0) abort();
- // размер файла фиксируется в момент mmap
- void * ptr = mmap(NULL, sz, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0); // offset - смещение
- if (ptr == MAP_FAILED) abort();
- //printf("YES\n");
- int *eptr = (int *) ((char*) ptr + sz * 4);
- int *cptr = (int *) (ptr);
- for (;cptr < eptr; ++cptr) {
- *cptr = -1;
- }
- long long k = 0;
- int i = 0, j = 0;
- enum Direct way = RIGHT;
- while (k < sz) {
- //printf("%d %d %lld\n", i, j, k + 1);
- int * cptr = (int *) ((char*) ptr + (i * cols + j) * 4);
- *cptr = k + 1;
- if (way == RIGHT) {
- if (j + 1 < cols) {
- int * next = (int *) ((char*) ptr + (i * cols + j + 1) * 4);
- if (*next == -1) {
- ++j;
- } else {
- way = DOWN;
- ++i;
- }
- } else {
- way = DOWN;
- ++i;
- }
- ++k;
- continue;
- }
- if (way == DOWN) {
- if (i + 1 < rows) {
- int * next = (int *) ((char*) ptr + ((i + 1) * cols + j) * 4);
- if (*next == -1) {
- ++i;
- } else {
- way = LEFT;
- --j;
- }
- } else {
- way = LEFT;
- --j;
- }
- ++k;
- continue;
- }
- if (way == LEFT) {
- if (j - 1 >= 0) {
- int * next = (int *) ((char*) ptr + (i * cols + j - 1) * 4);
- if (*next == -1) {
- --j;
- } else {
- way = UP;
- --i;
- }
- } else {
- way = UP;
- --i;
- }
- ++k;
- continue;
- }
- if (way == UP) {
- if (i - 1 >= 0) {
- int * next = (int *) ((char*) ptr + ((i - 1) * cols + j) * 4);
- if (*next == -1) {
- --i;
- } else {
- way = RIGHT;
- ++j;
- }
- } else {
- way = RIGHT;
- ++j;
- }
- ++k;
- continue;
- }
- }
- close(fd);
- munmap(ptr, st.st_size);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement