1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78
| func bfs(fff [][]byte, sx, sy, ex, ey, h, w int) int { vis := make([][][]bool, h) for i := 0; i < h; i++ { vis[i] = make([][]bool, w) for j := 0; j < w; j++ { vis[i][j] = make([]bool, 2) } }
type state struct { x, y, key, steps int } queue := []state{{sx, sy, 0, 0}} vis[sx][sy][0] = true dirs := [][2]int{ {-1, 0}, {1, 0}, {0, -1}, {0, 1}, }
for len(queue) > 0 { cur := queue[0] queue = queue[1:] x, y, key, steps := cur.x, cur.y, cur.key, cur.steps
if x == ex && y == ey { return steps }
for _, d := range dirs { nx, ny := x+d[0], y+d[1] if nx < 0 || nx >= h || ny < 0 || ny >= w { continue } cell := fff[nx][ny] if cell == 'W' { continue } nkey := key if cell == 'D' && key == 0 { continue } if cell == 'K' { nkey = 1 } if !vis[nx][ny][nkey] { vis[nx][ny][nkey] = true queue = append(queue, state{nx, ny, nkey, steps + 1}) } } } return -1 }
func sol() { var h,w int fmt.Scan(&h, &w) fff := make([][]byte, h) reader := bufio.NewReader(os.Stdin) var sx, sy, ex, ey int for i := 0; i < h; i++ { line, _ := reader.ReadString('\n') fff[i] = []byte(line[:len(line)-1]) for j := 0; j < w; j++ { if fff[i][j] == 'S' { sx, sy = i, j } else if fff[i][j] == 'E' { ex, ey = i, j } } } steps := bfs(fff, sx, sy, ex, ey, h, w) fmt.Println(steps) }
|