책에있는 연습문제 풀다가
첨으로 50줄 넘어간거라 올려봄ㅋㅋㅋㅋㅋㅋ
10x10판에서 A부터 Z까지 랜덤 방향으로 한칸씩 중복 없이 기어가는 코드임니다
중간에 길이 막히면 종료됨
#pragma warning(disable:4996)
#include <stdio.h>
#include <stdbool.h> // bool type, true and false
#include <time.h> // time function
#include <stdlib.h> // srand, rand function
#define SIZE 10 // board is 10x10
#define INITAL_CHARACTER 65
int main(void)
{
char board[SIZE + 2][SIZE + 2];
int i, j, step, move; // row, column, step of walks, direction of walk
bool possible_move[4] = { true,true,true,true }; // up, down, left, right
int check_block; // counts blocked moves
srand((unsigned)time(NULL)); // reset random generator
/* board initialization */
for (i = 0; i < SIZE+2; i++) {
for (j = 0; j < SIZE+2; j++)
board[i][j] = '.';
}
/* starting walk */
i = j = 1;
board[i][j] = (char) INITAL_CHARACTER;
for (step = 1; step < 26; step++) {
check_block = 0;
if (board[i - 1][j] != '.' || i == 1) {
possible_move[0] = false;
check_block++;
}
if (board[i + 1][j] != '.' || i == 10) {
possible_move[1] = false;
check_block++;
}
if (board[i][j - 1] != '.' || j == 1) {
possible_move[2] = false;
check_block++;
}
if (board[i][j + 1] != '.' || j == 10) {
possible_move[3] = false;
check_block++;
}
if (check_block == 4) {
break;
}
do { move = rand() % 4; } while (possible_move[move] == false);
switch (move)
{
case 0: i--; break;
case 1: i++; break;
case 2: j--; break;
case 3: j++; break;
}
board[i][j] = (INITAL_CHARACTER + step);
check_block = 0;
for (int t = 0; t < 4; t++)
possible_move[t] = true;
}
/* show board after walking */
for (i = 1; i < SIZE + 1; i++) {
for (j = 1; j < SIZE + 1; j++)
printf("%c ", board[i][j]);
printf("\n");
}
if (check_block == 4)
printf("Terminated due to no possible moves at letter %c.\n", INITAL_CHARACTER + step - 1);
else
printf("Ended Succesfully\n");
return 0;
}
댓글 0