Skip to content

Commit 085f44e

Browse files
committed
leetcode_1185_Day_of_the_Week
1 parent 105c465 commit 085f44e

File tree

2 files changed

+65
-0
lines changed

2 files changed

+65
-0
lines changed
Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
/**
2+
* Run depth first search
3+
*
4+
*/
5+
public class DepthFirstSearch {
6+
private boolean[] marked; // marked[v] = is there an s-v path?
7+
private int count; // number of vertices connected to s
8+
9+
// Computes the vertices in graph `G` that are connected to the source vertex `s`
10+
public DepthFirstSearch(Graph G, int s) {
11+
marked = new boolean[G.V()];
12+
validateVertex(s);
13+
dfs(G, s);
14+
}
15+
16+
// depth first search from v
17+
private void dfs(Graph G, int v) {
18+
count++;
19+
marked[v] = true;
20+
for(int w:G.adj(v)) {
21+
if(!marked[w])
22+
dfs(G, w);
23+
}
24+
}
25+
26+
// Is there a path between the source vertex `s` and vertex `v`?
27+
public boolean marked(int v) {
28+
validateVertex(v);
29+
return marked[v];
30+
}
31+
32+
// Returns the number of vertices connected to the source vertex `s`
33+
public int count() {
34+
return count;
35+
}
36+
37+
// throw an IllegalArgumentException unless `0 <= v < V`
38+
private void validateVertex(int v) {
39+
int V = marked.length;
40+
if(v < 0 || v >= V)
41+
throw new IllegalArgumentException("vertex " + V + "is not between 0 and " + (V - 1));
42+
}
43+
44+
// test
45+
public static void main(String[] args) {
46+
In in = new In(args[0]);
47+
Graph G = new Graph(in);
48+
int s = Integer.parseInt(args[1]);
49+
DepthFirstSearch search = new DepthFirstSearch(G, s);
50+
for(int v = 0; v < G.V(); v++) {
51+
if(search.marked(v))
52+
StdOut.print(v + " ");
53+
}
54+
55+
StdOut.println();
56+
if(search.count() != G.V())
57+
StdOut.println("NOT connected");
58+
else
59+
StdOut.println("connected");
60+
}
61+
}

leetcode_solved/leetcode_1185_Day_of_the_Week.cpp

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,8 @@
11
/**
2+
* AC: 最快的解法
3+
* Runtime: 0 ms, faster than 100.00% of C++ online submissions for Day of the Week.
4+
* Memory Usage: 8 MB, less than 100.00% of C++ online submissions for Day of the Week.
5+
*
26
* 思路:网上查到一个快捷公式。否则处理闰年的情况,代码会写很长。。这里偷鸡一下 :(
37
* 基姆拉尔森计算公式
48
* W= (d+2*m+3*(m+1)/5+y+y/4-y/100+y/400+1) mod 7

0 commit comments

Comments
 (0)