标签:
#include <stdio.h> #define ROCK 1 #define GOAL 3 int map[30][30]; int w,h; int dfsfind(int startx, int starty, int finx, int finy, int deep) { if (deep > 10) return -1; int min = 11; //往左边移动 if (startx > 0 && map[startx - 1][starty] != ROCK) { int tmpx = startx; while (tmpx > 0 && map[tmpx - 1][starty] != ROCK) { if (map[tmpx - 1][starty] == GOAL) { return 1; } tmpx --; } //若有石头 if (tmpx != 0) { int rockx = tmpx - 1; int rocky = starty; map[rockx][rocky] = 0; int tmpmin = dfsfind(tmpx, starty, finx, finy, deep + 1) + 1; map[rockx][rocky] = ROCK; if (tmpmin > 0 && min > tmpmin) { min = tmpmin; } } } //往右边移动 if (startx < h - 1 && map[startx + 1][starty] != ROCK) { int tmpx = startx; while (tmpx < h - 1 && map[tmpx + 1][starty] != ROCK) { if (map[tmpx + 1][starty] == GOAL) { return 1; } tmpx ++; } //若有石头 if (tmpx != h - 1) { int rockx = tmpx + 1; int rocky = starty; map[rockx][rocky] = 0; int tmpmin = dfsfind(tmpx, starty, finx, finy, deep + 1) + 1; map[rockx][rocky] = ROCK; if (tmpmin > 0 && min > tmpmin) { min = tmpmin; } } } //往上方移动 if (starty > 0 && map[startx][starty - 1] != ROCK) { int tmpy = starty; while (tmpy > 0 && map[startx][tmpy - 1] != ROCK) { if (map[startx][tmpy - 1] == GOAL) { return 1; } tmpy --; } //若有石头 if (tmpy != 0) { int rockx = startx; int rocky = tmpy - 1; map[rockx][rocky] = 0; int tmpmin = dfsfind(startx, tmpy, finx, finy, deep + 1) + 1; map[rockx][rocky] = ROCK; if (tmpmin > 0 && min > tmpmin) { min = tmpmin; } } } //往下移动 if (starty < w - 1 && map[startx][starty + 1] != ROCK) { int tmpy = starty; while (tmpy < w - 1 && map[startx][tmpy + 1] != ROCK) { if (map[startx][tmpy + 1] == GOAL) { return 1; } tmpy ++; } //若有石头 if (tmpy != w - 1) { int rockx = startx; int rocky = tmpy + 1; map[rockx][rocky] = 0; int tmpmin = dfsfind(startx, tmpy, finx, finy, deep + 1) + 1; map[rockx][rocky] = ROCK; if (tmpmin > 0 && min > tmpmin) { min = tmpmin; } } } return min < 11 ? min : -1; } int main(void) { int startx,starty; int finx,finy; while (scanf("%d%d", &w, &h)) { if (w == 0 && h == 0) break; for (int i = 0; i < h; i ++) { for (int j = 0; j < w; j ++) { scanf("%d", &map[i][j]); if (map[i][j] == 2) { startx = i; starty = j; } else if (map[i][j] == 3) { finx = i; finy = j; } } } int res = dfsfind(startx, starty, finx, finy, 0); printf("%d\n", res); } return 0; }
标签:
原文地址:http://www.cnblogs.com/shadowmydx/p/4346089.html