中级农民
- 积分
- 210
- 大米
- 颗
- 鳄梨
- 个
- 水井
- 尺
- 蓝莓
- 颗
- 萝卜
- 根
- 小米
- 粒
- 学分
- 个
- 注册时间
- 2016-10-26
- 最后登录
- 1970-1-1
|
这道题目粗看不难,但是readme.pdf中有几句提示值得玩味:
Try to think of the fastest, simplest code for length2Paths(). It's possible to do it with a relatively simple triply-nested loop. ... If your TA thinks your algorithm is too slow, you'll be asked to do it again.
那么问题来了,how to define fastest, simplest code?
我用两种不同的思路来解决这个问题:
(1)use a triply-nested loop with modification.
INSTEAD OF:- for( int u = 0; u < vertices; u++){
- for(int v = 0; v < vertices; v++) {
- for(int w = 0; w < vertices; w++){
- // set newGraph.adjMatrix[][].
复制代码 The running time is O(n^3). Thus, we need to improve the performance.
IMPROVEMENT:- //STEP 1: loop through the adjMatrix to determine the degree of each vertex, O(n^2).
- //STEP 2: loop through the adjMatrix to form the incidentEdges for each vertex, O(n^2). (NOTE: incidentEdges[i].length == degree(i) => save memory.)
- //STEP 3:
- for(int u = 0; u < vertices; u++) {
- for(int v : incidentEdges[u]) {
- for(int w : incidentEdges[v]){
- // set newGraph.adjMatrix[][].
复制代码 The running time is O(n^2 + n * max(degree(i))^2). Faster since degree(i) < n.
This implementation is much intuitive and clear.
(2) use BFS as someone suggested.
STEP1 loop through every vertex.
STEP1.1 start BFS from this vertex.
STEP1.2 get all vertices in the LEVEL length and set newGraph.adjMatrix.
The crux of this implementation: how to represent one vertex's LEVEL.
Originally, I used an int array to store the level info and update it according to the preceding vertex's.
However, it is WRONG. Because the same vertex can have the DIFFERENT level number and can COEXIST in the queue under certain circumstances.
For example, in the given test code, when length = 5.
Level 0 1 2 3 4 5
vertex 8->4->2->0->8->4
8->4->5->7
8->4->5->9->1->0
8->4->5->9->1->3
8->6->4->2->0->8
8->6->4->5->7
8->6->4->5->9
8->6->7
8->10->6->4->2
8->10->6->4->5
8->10->6->7
The running time is somewhat complicated, which I am unable to give the analysis.
|
|