Skip to content

Commit be4d7b3

Browse files
committed
Take advantage of predictable structure of graph to avoid DFS for topo sort
This is a first step toward avoiding having a separate function for topological sort so we can make it very fast.
1 parent 5a52924 commit be4d7b3

File tree

1 file changed

+13
-14
lines changed

1 file changed

+13
-14
lines changed

seamcarving/SeamCarver.java

+13-14
Original file line numberDiff line numberDiff line change
@@ -107,24 +107,23 @@ private void relax(int from, int to, double[] weights, double[] distTo, int[] ed
107107
}
108108
}
109109

110-
// Return the node IDs in topological order
110+
// Return the node IDs in topological order. Take advantage of predictable
111+
// structure of this graph to avoid doing DFS.
111112
private Iterable<Integer> toporder(int size) {
112-
Stack<Integer> toporder = new Stack<Integer>();
113-
boolean[] marked = new boolean[size];
114-
for (int id = 0; id < size; id++)
115-
if (!marked[id])
116-
dfs(id, marked, toporder);
113+
Queue<Integer> toporder = new Queue<Integer>();
114+
for (int startCol = width() - 1; startCol > 0; startCol--) {
115+
int col = startCol;
116+
for (int row = 0; row < height() && col < width(); row++)
117+
toporder.enqueue(node(col++, row));
118+
}
119+
for (int startRow = 0; startRow < height(); startRow++) {
120+
int row = startRow;
121+
for (int col = 0; col < width() && row < height(); col++)
122+
toporder.enqueue(node(col, row++));
123+
}
117124
return toporder;
118125
}
119126

120-
private void dfs(int v, boolean[] marked, Stack<Integer> toporder) {
121-
marked[v] = true;
122-
for (int w : adj(v))
123-
if (!marked[w])
124-
dfs(w, marked, toporder);
125-
toporder.push(v);
126-
}
127-
128127
// Mapping between node ID numbers and (col, row) notation. No bounds
129128
// checking is performed so use with caution.
130129
private int node(int col, int row) { return row * width() + col; }

0 commit comments

Comments
 (0)