- 1、有哪些信誉好的足球投注网站(book118)网站文档一经付费(服务费),不意味着购买了该文档的版权,仅供个人/单位学习、研究之用,不得用于商业用途,未经授权,严禁复制、发行、汇编、翻译或者网络传播等,侵权必究。。
- 2、本站所有内容均由合作方或网友上传,本站不对文档的完整性、权威性及其观点立场正确性做任何保证或承诺!文档内容仅供研究参考,付费前请自行鉴别。如您付费,意味着您自己接受本站规则且自行承担风险,本站不退款、不进行额外附加服务;查看《如何避免下载的几个坑》。如果您已付费下载过本站文档,您可以点击 这里二次下载。
- 3、如文档侵犯商业秘密、侵犯著作权、侵犯人身权等,请点击“版权申诉”(推荐),也可以打举报电话:400-050-0827(电话支持时间:9:00-18:30)。
查看更多
算法上机报告
算
法上
机
报
告
上机题目
1. 使用合并-查找数据结构,实现估计渗漏(Percolation)问题阈值的程序。
思路分析
使用union-found 算法,利用quick-union方法,定义一个N*N的矩阵,依次从1-N*N编号,在模拟渗漏问题时采用一种流动的思想,当按序号增大的顺序一次判断该块是否被打开,按照老师课件上的提示在顶部和底部各设置一个点,顶部点和第一排所有点都联通,底部点和最后一排所有点都联通,流动完之后判断这两个点是否联通即可。
源代码
package Assignments;
import java.util.Scanner;
public class Percolation
{
private boolean[] matrix;
private int row, col;
private WeightedQuickUnionUF wquUF;
private WeightedQuickUnionUF wquUFTop;
private boolean alreadyPercolates;
public Percolation(int N)
{
if (N 1)
throw new IllegalArgumentException(Illeagal Argument);
wquUF = new WeightedQuickUnionUF(N * N + 2);
wquUFTop = new WeightedQuickUnionUF(N * N + 1);
alreadyPercolates = false;
row = N;
col = N;
matrix = new boolean[N * N + 1];
}
private void validate(int i, int j)
{
if (i 1 || i row)
throw new IndexOutOfBoundsException(row index i out of bounds);
if (j 1 || j col)
throw new IndexOutOfBoundsException(col index j out of bounds);
}
public void open(int i, int j)
{
validate(i, j);
int curIdx = (i - 1) * col + j;
matrix[curIdx] = true;
if (i == 1)
{
wquUF.union(curIdx, 0);
wquUFTop.union(curIdx, 0);
}
if (i == row)
{
wquUF.union(curIdx, row * col + 1);
}
int[] dx =
{ 1, -1, 0, 0 };
int[] dy =
{ 0, 0, 1, -1 };
for (int dir = 0; dir 4; dir++)
{
int posX = i + dx[dir];
int posY = j + dy[dir];
if (posX = row posX = 1 posY = row posY = 1 isOpen(posX, posY))
{
wquUF.union(curIdx, (posX - 1) * col + posY);
wquUFTop.union(curIdx, (posX - 1) * col + posY);
}
}
}
public boolean isOpen(int i, int j)
{
validate(i, j);
return matrix[(i - 1) * col + j];
}
public boolean isFull(int i, int j)
{
validate(i, j);
int curIdx = (i - 1) * col + j;
if (wquUFTop.find(curIdx) == wquUFTop.find(0))
return true;
return false;
}
public boolean percolates()
{
if (alreadyPercolates)
return true;
if (wquUF.find(0) == wquUF.find(row * col + 1))
{
alreadyPercolates
文档评论(0)