Dashboard - Qualification Round 2009 - Google Code Jam
Given an elevation map (a 2-dimensional array of altitudes), label the map such that locations in the same drainage basin have the same label, subject to the following rules.
X: DFS
http://wilanw.blogspot.com/2009/09/google-code-jam-2009-qualification.html
The problem asks us to determine the different drainage basins given a heightmap as input. There is a set of rules in which the rainfall falls down to which is given in the problem statement. We can go through each cell and do a simple modified depth first search (really just recursion) once we reach the sink, we check whether or not the sink has been labelled. If it hasn't, then we label it with the next smallest unused lower-case character. We then backtrack and assign this character to all the nodes which were used to get to the sink. A simple optimisation is to stop recursing if we reach a node in which has already been assigned a lower-case letter as opposed to waiting until we reach the sink. This isn't required as the constraints are quite low (100x100) in the worst case.
There are some minor implementation details: we have to ensure that we consider adjacent nodes in the correct order (i.e. North, West, East, South). This is easily achieved by a direction array/vector which prioritises the order. This way we don't have to worry about the cases in which the lowest adjacent altitudes are equal, it's implicitly done for us. The constraint of placing the colour so the map is lexicographically smallest can be achieved by greedily filling in the nodes by row-order then by column-order. We are guaranteed to fill a cell with the smallest available character if we start traversing from (x,y) as it will eventually reach a sink. The last note is to not consider nodes that are outside the heightmap (nodes which exist outside the land) as well as not considering adjacent cells which have a height larger or equal to the current cell's height.
Apart from following the given rules - it's a straightforward simulation problem. The constraints are rather lenient, so any decent algorithm should pass within the time limits.
http://www.hankcs.com/program/qualification-round-2009-watersheds-die-dai-shi-xian.html
private class DisjointSetUnion {
int[] up;
public DisjointSetUnion(int n) {
up = new int[n];
for (int i = 0; i < n; i++) {
up[i] = i;
}
}
int up(int p) {
if (up[p] != p) {
up[p] = up(up[p]);
}
return up[p];
}
public void join(int a, int b) {
a = up(a);
b = up(b);
up[a] = b;
}
}
private class TestCaseSolver {
int n, m;
int[][] a, idx;
int[] dr = new int[] {-1, 0, 0, 1};
int[] dc = new int[] {0, -1, 1, 0};
private void solve() {
n = nextInt();
m = nextInt();
a = new int[n][m];
idx = new int[n][m];
for (int i = 0; i < n; i++)
for (int j = 0; j < m; j++) {
a[i][j] = nextInt();
idx[i][j] = i * m + j;
}
DisjointSetUnion dsu = new DisjointSetUnion(n * m);
for (int i = 0; i < n; i++)
for (int j = 0; j < m; j++) {
int lowest = Integer.MAX_VALUE;
int lowestI = 0;
int lowestJ = 0;
for (int k = 0; k < 4; k++) {
int ni = i + dr[k];
int nj = j + dc[k];
if (0 <= ni && ni < n && 0 <= nj && nj < m) {
if (a[ni][nj] < lowest) {
lowest = a[ni][nj];
lowestI = ni;
lowestJ = nj;
}
}
}
if (lowest < a[i][j]) {
dsu.join(idx[i][j], idx[lowestI][lowestJ]);
}
}
char letter = 'a';
Map<Integer, Character> done = new HashMap<Integer, Character>();
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
int component = dsu.up(idx[i][j]);
if (!done.containsKey(component)) {
done.put(component, letter++);
}
if (j > 0) {
out.print(' ');
}
out.print(done.get(component));
}
out.println();
}
}
}
http://www.stevekrenzel.com/articles/watersheds
https://github.com/lantoli/Google-Code-Jam/blob/master/05_Watersheds/Watersheds.java
Read full article from Dashboard - Qualification Round 2009 - Google Code Jam
Problem
Geologists sometimes divide an area of land into different regions based on where rainfall flows down to. These regions are called drainage basins. Given an elevation map (a 2-dimensional array of altitudes), label the map such that locations in the same drainage basin have the same label, subject to the following rules.
- From each cell, water flows down to at most one of its 4 neighboring cells.
- For each cell, if none of its 4 neighboring cells has a lower altitude than the current cell's, then the water does not flow, and the current cell is called a sink.
- Otherwise, water flows from the current cell to the neighbor with the lowest altitude.
- In case of a tie, water will choose the first direction with the lowest altitude from this list: North, West, East, South.
Input
The first line of the input file will contain the number of maps, T. T maps will follow, each starting with two integers on a line -- H and W -- the height and width of the map, in cells. The next H lines will each contain a row of the map, from north to south, each containing W integers, from west to east, specifying the altitudes of the cells.
Notes
In Case #1, the upper-right and lower-left corners are sinks. Water from the diagonal flows towards the lower-left because of the lower altitude (5 versus 6).
For each cell, we need to determine its eventual sink. Then, to each group of cells that share the same sink, we need to assign a unique label.
The inputs to this problem are small enough for a simple brute-force simulation algorithm. Start with a cell and trace the path that water would take by applying the water flow rules repeatedly.
X: DFS
http://wilanw.blogspot.com/2009/09/google-code-jam-2009-qualification.html
The problem asks us to determine the different drainage basins given a heightmap as input. There is a set of rules in which the rainfall falls down to which is given in the problem statement. We can go through each cell and do a simple modified depth first search (really just recursion) once we reach the sink, we check whether or not the sink has been labelled. If it hasn't, then we label it with the next smallest unused lower-case character. We then backtrack and assign this character to all the nodes which were used to get to the sink. A simple optimisation is to stop recursing if we reach a node in which has already been assigned a lower-case letter as opposed to waiting until we reach the sink. This isn't required as the constraints are quite low (100x100) in the worst case.
There are some minor implementation details: we have to ensure that we consider adjacent nodes in the correct order (i.e. North, West, East, South). This is easily achieved by a direction array/vector which prioritises the order. This way we don't have to worry about the cases in which the lowest adjacent altitudes are equal, it's implicitly done for us. The constraint of placing the colour so the map is lexicographically smallest can be achieved by greedily filling in the nodes by row-order then by column-order. We are guaranteed to fill a cell with the smallest available character if we start traversing from (x,y) as it will eventually reach a sink. The last note is to not consider nodes that are outside the heightmap (nodes which exist outside the land) as well as not considering adjacent cells which have a height larger or equal to the current cell's height.
Apart from following the given rules - it's a straightforward simulation problem. The constraints are rather lenient, so any decent algorithm should pass within the time limits.
int heightmap[111][111]; // matrix to keep track of the input height map char output[111][111]; // the final set of basins char comp; // the minimum un-used character component // directional vectors in preference of N, W, E, S int dx[] = {-1, 0, 0, 1}; int dy[] = {0, -1, 1, 0}; // the grid size - used for checking boundaries int szX, szY; char dfs(int x, int y) { // search for the lowest altitude given the rules defined // in the problem statement int lowest = 20000; int nx = -1, ny = -1; for (int k = 0; k < 4; k++) { int mx = dx[k] + x; int my = dy[k] + y; if (mx < 0 || my < 0 || mx >= szX || my >= szY || heightmap[x][y] <= heightmap[mx][my]) continue; if (heightmap[mx][my] < lowest) { lowest = heightmap[mx][my]; nx = mx; ny = my; } } // sink reached if (nx < 0) { if (output[x][y] != 0) return output[x][y]; return output[x][y] = comp++; } // backtrack the solution output[x][y] = dfs(nx,ny); } int main() { int T; cin >> T; for (int i = 0; i < T; i++) { memset(heightmap,0,sizeof(heightmap)); memset(output,0,sizeof(output)); int X, Y; cin >> X >> Y; for (int j = 0; j < X; j++) { for (int k = 0; k < Y; k++) { int val; cin >> val; heightmap[j][k] = val; } } // reset the dfs parameters comp = 'a'; szX = X; szY = Y; for (int j = 0; j < X; j++) { for (int k = 0; k < Y; k++) { // if we have assigned a character to the cell - don't need to dfs if (output[j][k]) continue; dfs(j,k); } } // output the assigned basins cout << "Case #" << (i+1) << ":\n"; for (int j = 0; j < X; j++) { for (int k = 0; k < Y; k++) { if (k != 0) cout << " "; cout << output[j][k]; } cout << "\n"; } } return 0; }
http://www.hankcs.com/program/qualification-round-2009-watersheds-die-dai-shi-xian.html
这道题目其实很简单,迭代就行了。大言不惭地说,迭代我最在行了。以前写过泡泡堂的地图引擎,比这个复杂多了。只要不StackOverflow,完全没问题。
思路很简单,两个二维数组,一个存海拔,一个存标签。遍历海拔数组,迭代流动,稍微有点麻烦的是方向的优先级
X. Union-Findprivate class DisjointSetUnion {
int[] up;
public DisjointSetUnion(int n) {
up = new int[n];
for (int i = 0; i < n; i++) {
up[i] = i;
}
}
int up(int p) {
if (up[p] != p) {
up[p] = up(up[p]);
}
return up[p];
}
public void join(int a, int b) {
a = up(a);
b = up(b);
up[a] = b;
}
}
private class TestCaseSolver {
int n, m;
int[][] a, idx;
int[] dr = new int[] {-1, 0, 0, 1};
int[] dc = new int[] {0, -1, 1, 0};
private void solve() {
n = nextInt();
m = nextInt();
a = new int[n][m];
idx = new int[n][m];
for (int i = 0; i < n; i++)
for (int j = 0; j < m; j++) {
a[i][j] = nextInt();
idx[i][j] = i * m + j;
}
DisjointSetUnion dsu = new DisjointSetUnion(n * m);
for (int i = 0; i < n; i++)
for (int j = 0; j < m; j++) {
int lowest = Integer.MAX_VALUE;
int lowestI = 0;
int lowestJ = 0;
for (int k = 0; k < 4; k++) {
int ni = i + dr[k];
int nj = j + dc[k];
if (0 <= ni && ni < n && 0 <= nj && nj < m) {
if (a[ni][nj] < lowest) {
lowest = a[ni][nj];
lowestI = ni;
lowestJ = nj;
}
}
}
if (lowest < a[i][j]) {
dsu.join(idx[i][j], idx[lowestI][lowestJ]);
}
}
char letter = 'a';
Map<Integer, Character> done = new HashMap<Integer, Character>();
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
int component = dsu.up(idx[i][j]);
if (!done.containsKey(component)) {
done.put(component, letter++);
}
if (j > 0) {
out.print(' ');
}
out.print(done.get(component));
}
out.println();
}
}
}
http://www.stevekrenzel.com/articles/watersheds
https://github.com/lantoli/Google-Code-Jam/blob/master/05_Watersheds/Watersheds.java
Read full article from Dashboard - Qualification Round 2009 - Google Code Jam