Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit25f19f8

Browse files
authored
Merge pull request#3340 from drxlx/1091-shortest-path-in-binary-matrix
Create 1091-shortest-path-in-binary-matrix.swift
2 parents85c0e81 +7777c32 commit25f19f8

File tree

1 file changed

+82
-0
lines changed

1 file changed

+82
-0
lines changed
Lines changed: 82 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,82 @@
1+
/**
2+
* Question Link: https://leetcode.com/problems/shortest-path-in-binary-matrix/
3+
*/
4+
5+
classListNode{
6+
letval:[Int]
7+
varnext:ListNode?
8+
9+
init(_ val:[Int]){
10+
self.val= val
11+
}
12+
}
13+
14+
classDequeue{
15+
varhead:ListNode?
16+
vartail:ListNode?
17+
varsize=0
18+
19+
func enqueue(_ val:[Int]){
20+
letnode=ListNode(val)
21+
if head==nil{
22+
head= node
23+
tail= node
24+
}else{
25+
tail?.next= node
26+
tail= tail?.next
27+
}
28+
29+
size+=1
30+
}
31+
32+
func deque()->[Int]?{
33+
if head==nil{
34+
returnnil
35+
}
36+
37+
letnode= head
38+
head= head?.next
39+
if head==nil{
40+
tail=nil
41+
}
42+
43+
size-=1
44+
return node!.val
45+
}
46+
}
47+
48+
classSolution{
49+
func shortestPathBinaryMatrix(_ grid:[[Int]])->Int{
50+
letrows= grid.count
51+
letcols=grid[0].count
52+
varvisit=Set<[Int]>()
53+
vardeque=Dequeue()
54+
visit.insert([0,0])
55+
deque.enqueue([0,0,1])
56+
57+
while deque.size>0{
58+
letval= deque.deque()!
59+
letr=val[0]
60+
letc=val[1]
61+
letlen=val[2]
62+
63+
if r<0 || c<0 || r== rows || c== cols ||grid[r][c]==1{
64+
continue
65+
}
66+
67+
if r== rows-1 && c== cols-1{
68+
return len
69+
}
70+
71+
letdirections=[(0,1),(0,-1),(1,0),(-1,0),(-1,-1),(1,1),(-1,1),(1,-1)]
72+
for(dr, dc)in directions{
73+
if !visit.contains([r+ dr, c+ dc]){
74+
deque.enqueue([r+ dr, c+ dc, len+1])
75+
visit.insert([r+ dr, c+ dc])
76+
}
77+
}
78+
}
79+
80+
return-1
81+
}
82+
}

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp