-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path043.swift
More file actions
148 lines (131 loc) · 3.22 KB
/
043.swift
File metadata and controls
148 lines (131 loc) · 3.22 KB
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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
class Cell {
let x: Int
let y: Int
let dir: Int
var pre: Cell?
var next: Cell?
init(x: Int, y: Int, dir: Int) {
self.x = x
self.y = y
self.dir = dir
}
}
class Deque {
var first: Cell?
var last: Cell?
var count = 0
func popFirst() -> Cell? {
if count == 0 {
return nil
} else {
let ret = first
if count == 1 {
first = nil
last = nil
} else {
first = first!.next
first!.pre = nil
ret!.next = nil
}
count -= 1
return ret
}
}
func popLast() -> Cell? {
if count == 0 {
return nil
} else {
let ret = last
if count == 1 {
first = nil
last = nil
} else {
last = last!.pre
last!.next = nil
ret!.pre = nil
}
count -= 1
return ret
}
}
func pushFirst(c: Cell) {
if count == 0 {
first = c
last = c
} else {
c.next = first
first!.pre = c
first = c
}
count += 1
}
func pushLast(c: Cell) {
if count == 0 {
first = c
last = c
} else {
c.pre = last
last!.next = c
last = c
}
count += 1
}
}
func readInts() -> [Int] {
readLine()!.split(separator: " ").map { Int(String($0))! }
}
let hw = readInts()
let h = hw[0]
let w = hw[1]
/*
縦がX軸
横がY軸
*/
let start = readInts()
let startX = start[0] - 1
let startY = start[1] - 1
let terminator = readInts()
let termiX = terminator[0] - 1
let termiY = terminator[1] - 1
var area: [[Bool]] = []
for _ in 1...h {
area.append(Array(readLine()!).map { $0 == "." })
}
//ある場所に、ある方向へ進行中に到達したとき、それまでに曲がった回数はいくつか
var dist = [[[Int]]](repeating: [[Int]](repeating: [Int](repeating: Int.max, count: 4), count: w), count: h)
let deq = Deque()
for i in 0..<4 {
dist[startX][startY][i] = 0
deq.pushLast(c: Cell(x: startX, y: startY, dir: i))
}
let dx = [1, 0, -1, 0]
let dy = [0, 1, 0, -1]
while let u = deq.popFirst() {
for i in 0..<4 {
let tx = u.x + dx[i]
let ty = u.y + dy[i]
if 0 <= tx, tx < h, 0 <= ty, ty < w, area[tx][ty] {
if u.dir == i {
//同一方向
let cost = dist[u.x][u.y][u.dir]
if cost < dist[tx][ty][i] {
dist[tx][ty][i] = cost
//注:Firstへpush
deq.pushFirst(c: Cell(x: tx, y: ty, dir: i))
}
} else {
//別方向
let cost = dist[u.x][u.y][u.dir] + 1
if cost < dist[tx][ty][i] {
dist[tx][ty][i] = cost
deq.pushLast(c: Cell(x: tx, y: ty, dir: i))
}
}
}
}
}
var answer = Int.max
for i in 0..<4 {
answer = min(answer, dist[termiX][termiY][i])
}
print(answer)