82 lines
2.0 KiB
C
82 lines
2.0 KiB
C
#include <stdio.h>
|
|
#include <stdlib.h>
|
|
#include <stdbool.h>
|
|
|
|
typedef struct {
|
|
int x, y, distance;
|
|
bool break_block;
|
|
} Node;
|
|
|
|
int main() {
|
|
int N, M;
|
|
scanf("%d %d", &N, &M);
|
|
|
|
int** map = (int**)malloc(sizeof(int*)*N);
|
|
bool*** visited = (bool***)malloc(sizeof(bool**)*N);
|
|
for(int i=0; i<N; i++) {
|
|
map[i] = (int*)malloc(sizeof(int)*M);
|
|
visited[i] = (bool**)malloc(sizeof(bool*)*M);
|
|
|
|
char line[M+2];
|
|
scanf("%s",line);
|
|
|
|
for(int j=0; j<M; j++) {
|
|
map[i][j] = line[j] - '0';
|
|
visited[i][j] = (bool*)calloc(2, sizeof(bool));
|
|
}
|
|
}
|
|
|
|
Node* qu = (Node*)malloc(sizeof(Node)*(N*M*2));
|
|
int front = 0, rear = 0;
|
|
Node start = {0, 0, 1, false};
|
|
visited[0][0][0] = true;
|
|
qu[rear++] = start;
|
|
|
|
int dx[4] = {-1,1,0,0};
|
|
int dy[4] = {0,0,1,-1};
|
|
int result = -1;
|
|
|
|
while(front != rear) {
|
|
Node now = qu[front++];
|
|
int cx = now.x, cy = now.y, cd = now.distance;
|
|
bool isBreakBlock = now.break_block;
|
|
|
|
if(cx==M-1 && cy==N-1) {
|
|
result = cd;
|
|
break;
|
|
}
|
|
|
|
for(int i=0; i<4; i++) {
|
|
int nx = cx + dx[i], ny = cy + dy[i], nd = cd + 1;
|
|
|
|
if(nx<0 || nx>=M || ny<0 || ny>=N) continue;
|
|
|
|
bool isWall = map[ny][nx] == 1;
|
|
|
|
if(isWall && isBreakBlock) continue;
|
|
|
|
bool next_block_state = isWall || isBreakBlock; // (isWall && !isBreakBlock) || isBreakBlock을 단순화한 값
|
|
int block_state_index = next_block_state ? 1 : 0;
|
|
|
|
if(!visited[ny][nx][block_state_index]) {
|
|
Node next = {nx, ny, nd, next_block_state};
|
|
qu[rear++] = next;
|
|
visited[ny][nx][block_state_index] = true;
|
|
}
|
|
}
|
|
}
|
|
|
|
printf("%d\n",result);
|
|
|
|
for(int i=0; i<N; i++) {
|
|
free(map[i]);
|
|
for(int j=0; j<M; j++) free(visited[i][j]);
|
|
free(visited[i]);
|
|
}
|
|
|
|
free(map);
|
|
free(visited);
|
|
free(qu);
|
|
|
|
return 0;
|
|
} |