Skip to content

Commit be2f788

Browse files
committed
graph
1 parent 87cd7f9 commit be2f788

31 files changed

Lines changed: 747 additions & 46 deletions

Graph/0-1 BFS/Edge Reverse.py

Lines changed: 85 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,85 @@
1+
# https://maang.in/problems/Edge-Reverse-900?resourceUrl=cs214-cp873-pl3343-rs900&returnUrl=%5B%22%2Fcourses%2FGraph-Level-1-214%3Ftab%3Dchapters%22%5D
2+
3+
'''
4+
Description
5+
Given a directed graph with N vertices and M edges. What is the minimum number of edges needed to reverse in order to have at least one path from vertex 1 to vertex N, where the vertices are numbered from 1 to N?
6+
7+
Input Format
8+
The first line contains T - the number of test cases.
9+
The first line of each test case contains two space-separated integers N and M, denoting the number of vertices and the number of edges in the graph respectively. The ithith line of the next M lines of each test case contains two space-separated integers Xi and Yi, denoting that the ithith edge connects vertices from Xi to Yi.
10+
Output Format
11+
For each test case, in a single line, print the minimum number of edges we need to revert. If there is no way of having at least one path from 1 to N, print −1.
12+
13+
Constraints
14+
1≤T≤10
15+
1≤N,M≤105
16+
1≤Xi,Yi≤N
17+
There can be multiple edges connecting the same pair of vertices. There can be self-loops too, i.e., Xi=Yi.
18+
19+
Sample Input 1
20+
1
21+
7 7
22+
1 2
23+
3 2
24+
3 4
25+
7 4
26+
6 2
27+
5 6
28+
7 5
29+
Sample Output 1
30+
2
31+
'''
32+
33+
# Write your code here
34+
import sys
35+
from collections import deque
36+
37+
input = sys.stdin.readline
38+
INF = 10**18
39+
40+
41+
def solve():
42+
t = int(input())
43+
ans = []
44+
45+
for _ in range(t):
46+
n, m = map(int, input().split())
47+
48+
adj = [[] for _ in range(n + 1)]
49+
50+
for _ in range(m):
51+
u, v = map(int, input().split())
52+
53+
adj[u].append((v, 0)) # original edge
54+
adj[v].append((u, 1)) # reversed edge
55+
56+
dist = [INF] * (n + 1)
57+
dist[1] = 0
58+
59+
dq = deque([1])
60+
61+
while dq:
62+
node = dq.popleft()
63+
64+
for nei, cost in adj[node]:
65+
if dist[node] + cost < dist[nei]:
66+
dist[nei] = dist[node] + cost
67+
68+
if cost == 0:
69+
dq.appendleft(nei)
70+
else:
71+
dq.append(nei)
72+
73+
ans.append(str(dist[n] if dist[n] != INF else -1))
74+
75+
sys.stdout.write("\n".join(ans))
76+
77+
78+
if __name__ == "__main__":
79+
solve()
80+
81+
'''
82+
Time Complexity per test case: O(N+M).
83+
84+
Space Complexity per test case: O(N+M).
85+
'''

Graph/0-1 BFS/One Piece.py

Lines changed: 103 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,103 @@
1+
# https://maang.in/problems/One-Piece-902?resourceUrl=cs214-cp873-pl3343-rs902&returnUrl=%5B%22%2Fcourses%2FGraph-Level-1-214%3Ftab%3Dchapters%22%5D
2+
3+
'''
4+
Description
5+
Monkey D. Luffy, on his journey of becoming the "King of Pirates" and to conquer the "One Piece", wants to travel across the Grand Line. Grand Line is a mysterious sea, and is in the shape of a N×M grid S with every cell denoting the wind direction. The sign of
6+
S[i][j] can be: 1 which means wind in the cell flows to the right (i.e. from
7+
S[i][j] to
8+
S[i][j+1]), 2 which means wind in the cell flows to the left (i.e. from
9+
S[i][j] to
10+
S[i][j−1]),
11+
3 which means wind in the cell flows downwards (i.e. from
12+
S[i][j] to
13+
S[i+1][j]), or
14+
4 which means wind in the cell flows upwards (i.e. from
15+
S[i][j] to
16+
S[i−1][j]). Notice that there could be some signs on the cells of the grid
17+
S that point outside the Grand Line sea grid.
18+
19+
Merry, Luffy's ship, can only sail along the wind direction and cannot go outside the Grand Line sea grid
20+
S at any point. Luffy can modify the wind's direction on a cell with a
21+
cost=1 (he can modify the sign on a cell one time only).
22+
23+
Find the minimum cost to make Luffy's voyage from the top-left corner of the Grand Line, i.e.,
24+
S[1][1], to its bottom-right corner, i.e.,
25+
S[N][M], possible.
26+
27+
Input Format
28+
Input is given from Standard Input in the following format:
29+
S 1,1 S 1,2
30+
​ …S
31+
1,M
32+
33+
Output Format
34+
Print the minimum total cost required to make a path from
35+
S[1][1] to
36+
S[N][M].
37+
38+
Constraints
39+
2≤N,M≤1000.
40+
N and M are integers.
41+
42+
Sample Input 1
43+
4 4
44+
1 1 1 1
45+
2 2 2 2
46+
1 1 1 1
47+
2 2 2 2
48+
Sample Output 1
49+
3
50+
Sample Input 2
51+
3 3
52+
1 1 3
53+
3 2 2
54+
1 1 4
55+
Sample Output 2
56+
0
57+
'''
58+
# Write your code here
59+
import sys
60+
from collections import deque
61+
62+
input=sys.stdin.readline
63+
64+
INF=10**18
65+
66+
dirs=[
67+
(0,1),
68+
(0,-1),
69+
(1,0),
70+
(-1,0)
71+
]
72+
73+
def solve():
74+
n,m=list(map(int,input().split()))
75+
grid=[]
76+
for _ in range(n):
77+
grid.append(list(map(int,input().split())))
78+
79+
dist=[[INF]*m for _ in range(n)]
80+
dist[0][0]=0
81+
82+
q=deque([(0,0)])
83+
while q:
84+
x,y=q.popleft()
85+
for k in range(4):
86+
nx,ny=x+dirs[k][0],y+dirs[k][1]
87+
if 0<=nx<n and 0<=ny<m:
88+
cost=0 if grid[x][y]==k+1 else 1
89+
if dist[x][y]+cost<dist[nx][ny]:
90+
dist[nx][ny]=cost+dist[x][y]
91+
if cost==0:
92+
q.appendleft((nx,ny))
93+
else:
94+
q.append((nx,ny))
95+
print(dist[n-1][m-1])
96+
97+
if __name__=="__main__":
98+
solve()
99+
100+
101+
# Time Complexity per test case: O(N×M) because each cell is processed at most a constant number of times and there are 4 edges per cell.
102+
103+
# Space Complexity per test case: O(N×M) for the distance matrix and the deque.
File renamed without changes.
File renamed without changes.

Graph/DFS & BFS/1466. Reorder Routes to Make All Paths Lead to the City Zero.py renamed to Graph/DFS/1466. Reorder Routes to Make All Paths Lead to the City Zero.py

File renamed without changes.

Graph/DFS & BFS/1625. Lexicographically Smallest String After Applying Operations.py renamed to Graph/DFS/1625. Lexicographically Smallest String After Applying Operations.py

File renamed without changes.

0 commit comments

Comments
 (0)