迷路を駆け抜けろ
迷路を解くよ!
S - スタート地点
G - ゴール地点
□ - 通った通路
■ - 壁
右手で壁をつたいながら移動していっている(はず!)
ちょっとした頭の体操にはもってこいですね。
マップの作り方によってはセグメントエラーが起きる。
あとで直す。多分。
map.txtの内容
最初の2つの数 -- 横幅 縦幅
0 - 通路
1 - スタート
2 - ゴール
3 - 壁
以下ソース
#include <stdio.h> #include <string.h> char map[50][50]; int width, height; void read_map(void) { FILE* map_file; char buf[30]; int w, h; map_file = fopen("map.txt", "r"); if (map_file == NULL) { printf("map.txt が開けませんでした.\n"); exit(1); } memset(map, '3', sizeof(map)); fgets(buf, sizeof(buf), map_file); sscanf(buf, "%d %d", &width, &height); for (h = 1;h <= height;h++) fgets(map[h]+1, sizeof(map[h]), map_file); } int calc(void) { int x, y, dir = 2; int i, j; int dx[] = {0, -1, 0, 1}; int dy[] = {-1, 0, 1, 0}; for (i = 0;i < height;i++) { for (j = 0;j < width;j++) { if (map[i][j] == '1') { x = j; y = i; } } } while (1) { for (int i=0;i < 4;i++) { if (map[y+dy[(dir+3)%4]][x+dx[(dir+3)%4]] != '3') { dir = (dir+3)%4; break; } else if (map[y+dy[dir]][x+dx[dir]] != '3') { break; } else { dir = (dir+1)%4; } } if (map[y][x] != '1') map[y][x] = '4'; y = y + dy[dir]; x = x + dx[dir]; if (map[y][x] == '2') return 1; else if (map[y][x] == '1') return 0; } } int main(void) { char *symbol[] = {" ", "S", "G", "■", "□"}; read_map(); if (calc()) printf("ゴール出来たみたいです.\n"); else printf("ゴール出来ないみたいです.....\n"); for (int i=1;i <= height;i++) { for (int j=1;j <= width;j++) { printf("%s", symbol[map[i][j]-'0']); } printf("\n"); } return 0; } //map.txt 35 21 31333333333333333333333333333333333 30300030000000003000300030003000003 30303030333333333030303330303330333 30303030000000003030303000300030003 30303033333333303033303033333033303 30003000000030003000303000003033303 33333333303030333330303033303033303 30000000303030000030303030003033303 30333330333033303030000030303033333 30300000300030003033333330303000003 30333333303330333033333330333333303 30000030300000300000000030000030003 30303030333333333333303333333030333 30303030000000300000000000003030003 30333030303330303333333333333030303 30003000300030300000000030000030303 33303333333030333333333030333333303 30003030000030300030003000300000303 30333030333330303030303033333330303 30000030000030003000300000000000303 33333333333333333333333333333333323
もっとすっきりしたソースを書きたい。 コメントがないのはご愛嬌