3种版本的答案,第一种使用virtual top and bottom site, 但有backwash的问题,解决这个问题有两种方法:

1. 使用2个WQUUF, 但会增加memory. One for checking if the system percolates(include virtual top and bottom), and the other to check if a given cell is full(only include virtual top). 而且要注意,判断site 是否open只能用boolean ,不然memory 就会超出限制。记住:选择合适的data structure 很重要!!

2. 仍然使用1个WQUUF, 但不使用virtual top and bottom site, 增加判断connect to top 和connect to bottom, 如果出现site 既connect to top 也connect to bottom, 那么percolate.

I found a solution that works really well, that helped me to get bonus points. The general idea is to use only one WQUUF (N*N) and an array (N*N) that contains info about site status. 
We create ONE WQUUF object of size N * N, and allocate a separate array of size N * N to keep the status of each site: blocked, open, connect to top, connect to bottom. I use bit operation for the status so for each site, it could have combined status like Open and connect to top.
 
The most important operation is open(int i, int j): we need to union the newly opened site (let’s call it site ‘S’) S with the four adjacent neighbor sites if possible. For each possible neighbor site(Let’s call it ‘neighbor’), we first call find(neighbor) to get the root of that connected component, and retrieves the status of that root (Let’s call it ‘status’), next, we do Union(S, neighbor); we do the similar operation for at most 4 times, and we do a 5th find(S) to get the root of the newly (copyright @sigmainfy) generated connected component results from opening the site S, finally we update the status of the new root by combining the old status information into the new root in constant time. I leave the details of how to combine the information to update the the status of the new root to the readers, which would not be hard to think of.
 
For the isFull(int i, int j), we need to find the the root site in the connected component which contains site (i, j) and check the status of the root. 
For the isOpen(int i, int j) we directly return the status.
For percolates(), there is a way to make it constant time even though we do not have virtual top or bottom sites: think about why?
So the most important operation  open(int i, int j) will involve 4 union() and 5 find() API calls.
 
I am working on this but I think I understand it. Don't use virtual sites. Find(p) returns the same value for every p in the same component. For every open, call find(p) on neighbors and note down the status of each of the roots of neighbors. I( use a byte array where 0 is closed ; 1 is open. 2 is connectedness to top; 3 is connected to bottom and 4 is both.)

If any of the neighbors have connected to both set or (at least 1 is connected to top AND atleast 1 is connected to bottom) then set some local flag both to true

If connected to top is true set local flag top to true If connected to bottom is true set local flag bottom to true

Now after the unions with neighbors, find root of (I,j) And set its grid status to both or top or bottom.

If you do set it to both then you can also set a class variable percolatesFlag to true for use in the method percolates.

I haven't finished my implementation but it does seem like this will work.


java code

1. 有backwash

import edu.princeton.cs.algs4.WeightedQuickUnionUF;

public class Percolation {
private boolean[] openSite; //if open is 1 , block 0
private int N; //create N-by-N grid
private WeightedQuickUnionUF uf;
private int top;
private int bottom; public Percolation(int N) { // create N-by-N grid, with all sites blocked
if (N <= 0) {
throw new IllegalArgumentException("N must be bigger than 0");
}
this.N = N;
uf = new WeightedQuickUnionUF(N*N + 2);
openSite = new boolean[N*N+2]; // 0 top_visual N*N+1 bottom_visual
top = 0;
bottom = N*N +1;
for (int i = 1; i <= N*N; i++) {
openSite[i] = false; //initial all sites block
}
} public void open(int i, int j) { // open site (row i, column j) if it is not open already
validateIJ(i, j);
int index = xyTo1D(i, j);
openSite[index] = true; if (i == 1) {
uf.union(index, top);
}
if (!percolates()) {
if (i == N) {
uf.union(index, bottom);
}
}
if (i < N && openSite[index+N]) {
uf.union(index, index+N);
}
if (i > 1 && openSite[index-N]) {
uf.union(index, index-N);
}
if (j < N && openSite[index+1]) {
uf.union(index, index+1);
}
if (j > 1 && openSite[index-1]) {
uf.union(index, index-1);
} } private int xyTo1D(int i, int j) {
validateIJ(i, j);
return j + (i-1) * N;
} private void validateIJ(int i, int j) {
if (!(i >= 1 && i <= N && j >= 1 && j <= N)) {
throw new IndexOutOfBoundsException("Index is not betwwen 1 and N");
}
} public boolean isOpen(int i, int j) { // is site (row i, column j) open?
validateIJ(i, j);
return openSite[xyTo1D(i, j)];
} /*A full site is an open site that can be connected to an open site in the top row
* via a chain of neighboring (left, right, up, down) open sites.
*/
public boolean isFull(int i, int j) { // is site (row i, column j) full?
validateIJ(i, j);
return uf.connected(top, xyTo1D(i, j));
} /* Introduce 2 virtual sites (and connections to top and bottom).
* Percolates iff virtual top site is connected to virtual bottom site.
*/
public boolean percolates() { // does the system percolate?
return uf.connected(top, bottom);
} public static void main(String[] args) { // test client (optional)
}
}

2. 使用2个WQUUF

//use two WQUUF
//One way to fix this is two use two different WQUF.
//One for checking if the system percolates(include virtual top and bottom ),
//and the other to check if a given cell is full(only include virtual top). import edu.princeton.cs.algs4.WeightedQuickUnionUF; public class Percolation {
private boolean[] openSite; //if open is true , block false
private int N; //create N-by-N grid
private WeightedQuickUnionUF uf;
private WeightedQuickUnionUF ufNoBottom;
private int top;
private int bottom; public Percolation(int N) { // create N-by-N grid, with all sites blocked
if (N <= 0) {
throw new IllegalArgumentException("N must be bigger than 0");
}
this.N = N;
uf = new WeightedQuickUnionUF(N*N + 2);
ufNoBottom = new WeightedQuickUnionUF(N*N + 1);
openSite = new boolean[N*N+2]; // 0 top_visual N*N+1 bottom_visual
top = 0;
bottom = N*N +1;
for (int i = 1; i <= N*N; i++) {
openSite[i] = false; //initial all sites block
}
} public void open(int i, int j) { // open site (row i, column j) if it is not open already
validateIJ(i, j);
int index = xyTo1D(i, j);
openSite[index] = true; if (i == 1) {
uf.union(index, top);
ufNoBottom.union(index, top);
}
if (!percolates()) {
if (i == N) {
uf.union(index, bottom);
}
}
if (i < N && openSite[index+N]) {
uf.union(index, index+N);
ufNoBottom.union(index, index+N);
}
if (i > 1 && openSite[index-N]) {
uf.union(index, index-N);
ufNoBottom.union(index, index-N);
}
if (j < N && openSite[index+1]) {
uf.union(index, index+1);
ufNoBottom.union(index, index+1);
}
if (j > 1 && openSite[index-1]) {
uf.union(index, index-1);
ufNoBottom.union(index, index-1);
}
} private int xyTo1D(int i, int j) {
validateIJ(i, j);
return j + (i-1) * N;
} private void validateIJ(int i, int j) {
if (!(i >= 1 && i <= N && j >= 1 && j <= N)) {
throw new IndexOutOfBoundsException("Index is not betwwen 1 and N");
}
} public boolean isOpen(int i, int j) { // is site (row i, column j) open?
validateIJ(i, j);
return openSite[xyTo1D(i, j)];
} /*A full site is an open site that can be connected to an open site in the top row
* via a chain of neighboring (left, right, up, down) open sites.
*/
public boolean isFull(int i, int j) { // is site (row i, column j) full?
validateIJ(i, j);
return ufNoBottom.connected(top, xyTo1D(i, j));
} /* Introduce 2 virtual sites (and connections to top and bottom).
* Percolates iff virtual top site is connected to virtual bottom site.
*/
public boolean percolates() { // does the system percolate?
return uf.connected(top, bottom);
} public static void main(String[] args) { // test client (optional)
}
}

3. 最佳方法,增加flag, 只使用1个WQUUF

//use one WQUUF to avoid backwash
import edu.princeton.cs.algs4.WeightedQuickUnionUF; public class Percolation {
private boolean[] open; //blocked: false, open: true
private boolean[] connectTop;
private boolean[] connectBottom;
private int N; //create N-by-N grid
private WeightedQuickUnionUF uf;
private boolean percolateFlag; public Percolation(int N) { // create N-by-N grid, with all sites blocked
if (N <= 0) {
throw new IllegalArgumentException("N must be bigger than 0");
}
this.N = N;
uf = new WeightedQuickUnionUF(N*N);
open = new boolean[N*N];
connectTop = new boolean[N*N];
connectBottom = new boolean[N*N]; for (int i = 0; i < N*N; i++) {
open[i] = false;
connectTop[i] = false;
connectBottom[i] = false;
}
percolateFlag = false;
} public void open(int i, int j) { // open site (row i, column j) if it is not open already
validateIJ(i, j);
int index = xyTo1D(i, j);
open[index] = true; //open
boolean top = false;
boolean bottom = false; if (i < N && open[index+N]) {
if (connectTop[uf.find(index+N)] || connectTop[uf.find(index)] ) {
top = true;
}
if (connectBottom[uf.find(index+N)] || connectBottom[uf.find(index)] ) {
bottom = true;
}
uf.union(index, index+N);
}
if (i > 1 && open[index-N]) {
if (connectTop[uf.find(index-N)] || connectTop[uf.find(index)] ) {
top = true;
}
if (connectBottom[uf.find(index-N)] || connectBottom[uf.find(index)] ) {
bottom = true;
}
uf.union(index, index-N);
}
if (j < N && open[index+1]) {
if (connectTop[uf.find(index+1)] || connectTop[uf.find(index)] ) {
top = true;
}
if (connectBottom[uf.find(index+1)] || connectBottom[uf.find(index)] ) {
bottom = true;
}
uf.union(index, index+1);
}
if (j > 1 && open[index-1]) {
if (connectTop[uf.find(index-1)] || connectTop[uf.find(index)] ) {
top = true;
}
if (connectBottom[uf.find(index-1)] || connectBottom[uf.find(index)] ) {
bottom = true;
}
uf.union(index, index-1);
}
if(i == 1) {
top = true;
}
if(i == N){
bottom = true;
}
connectTop[uf.find(index)] = top;
connectBottom[uf.find(index)] = bottom;
if( connectTop[uf.find(index)] && connectBottom[uf.find(index)]) {
percolateFlag = true;
}
} private int xyTo1D(int i, int j) {
validateIJ(i, j);
return j + (i-1) * N -1;
} private void validateIJ(int i, int j) {
if (!(i >= 1 && i <= N && j >= 1 && j <= N)) {
throw new IndexOutOfBoundsException("Index is not betwwen 1 and N");
}
} public boolean isOpen(int i, int j) { // is site (row i, column j) open?
validateIJ(i, j);
return open[xyTo1D(i, j)];
} /*A full site is an open site that can be connected to an open site in the top row
* via a chain of neighboring (left, right, up, down) open sites.
*/
public boolean isFull(int i, int j) { // is site (row i, column j) full?
validateIJ(i, j);
return connectTop[uf.find(xyTo1D(i, j))];
} /* Introduce 2 virtual sites (and connections to top and bottom).
* Percolates iff virtual top site is connected to virtual bottom site.
*/
public boolean percolates() { // does the system percolate?
return percolateFlag;
} public static void main(String[] args) { // test client (optional)
}
}

Reference:

1. http://tech-wonderland.net/blog/avoid-backwash-in-percolation.html

AlgorithmsI Programming Assignment 1: Percolation的更多相关文章

  1. Programming Assignment 1: Percolation

    问题描述可以详见:http://coursera.cs.princeton.edu/algs4/assignments/percolation.html 关于QuickFindUF的javadoc:h ...

  2. AlgorithmsI Programming Assignment 1: PercolationStats.java

    import edu.princeton.cs.algs4.StdOut; import edu.princeton.cs.algs4.StdRandom; import edu.princeton. ...

  3. Coursera Algorithms Programming Assignment 1: Percolation(100分)

    题目来源http://coursera.cs.princeton.edu/algs4/assignments/percolation.html 作业分为两部分:建立模型和仿真实验. 最关键的部分就是建 ...

  4. 课程一(Neural Networks and Deep Learning),第三周(Shallow neural networks)—— 3.Programming Assignment : Planar data classification with a hidden layer

    Planar data classification with a hidden layer Welcome to the second programming exercise of the dee ...

  5. Algorithms: Design and Analysis, Part 1 - Programming Assignment #1

    自我总结: 1.编程的思维不够,虽然分析有哪些需要的函数,但是不能比较好的汇总整合 2.写代码能力,容易挫败感,经常有bug,很烦心,耐心不够好 题目: In this programming ass ...

  6. Algorithms : Programming Assignment 3: Pattern Recognition

    Programming Assignment 3: Pattern Recognition 1.题目重述 原题目:Programming Assignment 3: Pattern Recogniti ...

  7. Programming Assignment 2: Randomized Queues and Deques

    实现一个泛型的双端队列和随机化队列,用数组和链表的方式实现基本数据结构,主要介绍了泛型和迭代器. Dequeue. 实现一个双端队列,它是栈和队列的升级版,支持首尾两端的插入和删除.Deque的API ...

  8. 课程一(Neural Networks and Deep Learning),第二周(Basics of Neural Network programming)—— 2、编程作业常见问题与答案(Programming Assignment FAQ)

    Please note that when you are working on the programming exercise you will find comments that say &q ...

  9. Programming Assignment 5: Kd-Trees

    用2d-tree数据结构实现在2维矩形区域内的高效的range search 和 nearest neighbor search.2d-tree有许多的应用,在天体分类.计算机动画.神经网络加速.数据 ...

随机推荐

  1. div宽度设置无效问题解决

    问题描述: 要设置两个div在同一行显示,都加入了display:inline样式,但是其中一个div的宽度设置无效,在浏览器显示它的宽度始终是1003px. 解决办法: 方法1/给div加入样式:f ...

  2. C# 二叉查找树实现

    BuildTree 代码1次CODE完,没有BUG. 在画图地方debug了很多次.第一次画这种图. 一开始用treeview显示,但发现不是很好看出树结构,于是自己动手画了出来. using Sys ...

  3. JS escape()、encodeURI()和encodeURIComponent()的区别

    1.实例说明: var url='http://wx.jnqianle.com/content/images/冰皮月饼.jpg?name=张三丰&age=11'; console.info(w ...

  4. Android--WebView控件

    WebView 一 简介: WebView一般用于将Android页面已HTML的形式展现,我们一般叫它HTML5开发: WebView可以使得网页轻松的内嵌到app里,还可以直接跟js相互调用,通过 ...

  5. VB热点答疑(2016.5.11更新Q4、Q5)

    收录助教君在VB习题课上最常被问到的问题,每周更新,希望对大家有所帮助. Q1.如何让新的文本内容接在原来的内容后面/下一行显示? A1.例如,Label1.text原本的内容是"VB程序设 ...

  6. C++函数二义性问题,我怎么感觉编译器有偷懒嫌疑!!!

    瞎扯一段,讲得不一定对.纯属学习! struct BB{ void a(){ cout << "bb's a()\n"; }}; struct B1 : public ...

  7. php开发利器

    phpstorm 当前版本2016.1 之前用的为Zend studio,比之notepad++确实方便很多,不过很多方面还是不方便的,比如定位文件,上传下载到svn什么的. 看到phpstorm新版 ...

  8. LAMP的编译日志,

    在CentOS5.2上,编译LAMP的,两年前测试通过的,现在留印 ### 在记事本中 ,不要打开 自动换行,否则一些命令 无法正常运行###把源文件考到/src/目录下,然后进入/src////// ...

  9. [转]我的第一个WCF

    1:首先新建一个解决方案 2:右击解决方案添加一个控制台程序 3:对着新建好的控制台程序右击添加wcf服务 最后的结果: 有3个文件 app.config  Iwcf_server.cs wcf_se ...

  10. 为什么使用"use strict"可以节约你的时间

    转: http://ourjs.com/detail/52f572bf4534c0d806000024 "use strict"是JavaScript中一个非常好的特性,而且非常容 ...