Algs4-1.4.19矩阵的局部最小元素
1.4.19矩阵的局部最小元素。给定一个含 有N^2个不同整数的NXN数组a[]。设计一个运行时间和N成正比的算法来找出一个局部最小元素:满足a[i][j]<a[i+1][j]、a[i][j]<a[i][j+1]、a[i][j]<a[i-1][j]以及a[i][j]<a[i][j-1]的索引i和j。程序的运行时间在最坏情况下应该和N成正比。
Local minimum of a matrix. Given an N-by-N array a[] of N2 distinct integers, design an algorithm that runs in time proportional to N to find a local minimum: an pair of indices i and j such that a[i][j] < a[i+1][j], a[i][j] < a[i][j+1], a[i][j] < a[i-1][j], and a[i][j] < a[i][j-1] (assuming the neighboring entry is in bounds).
Hint: Find the minimum entry in row N/2, say a[N/2][j]. Check its two vertical neighbors a[N/2-1][j] and a[N/2+1][j]. Recur in the half with the smaller neighbor. In that half, find the minimum entry in column N/2.
答:
public class E1d4d19
{
public static void min(int[][] a)
{
int Rlo=1;
int Rhi=a.length;
int Rmid;
//
int Clo=1;
int Chi=a[0].length;
int Cmid;
while(Rlo<Rhi && Clo<Chi)
{
Rmid=(Rlo+Rhi)/2;
Cmid=(Clo+Chi)/2;
if(a[Rmid-1][Cmid]<a[Rmid][Cmid])
Rhi=Rmid-1;
else if(a[Rmid][Cmid]>a[Rmid+1][Cmid])
Rlo=Rmid+1;
else if(a[Rmid][Cmid-1]<a[Rmid][Cmid])
Chi=Cmid-1;
else if(a[Rmid][Cmid]>a[Rmid][Cmid+1])
Clo=Cmid+1;
else
{
StdOut.printf("row=%d,col=%d",Rmid,Cmid);
return ;
}
}
StdOut.print("can't find");
}
public static void main(String[] args)
{
int N=Integer.parseInt(args[0]);
int[][] a=new int[N][N];
int k=0;
for(int i=0;i<N;i++)
{
for(int j=0;j<N;j++)
{
a[i][j]=StdRandom.uniform(N*N);//数组值会有重复。
StdOut.printf("%6d ",a[i][j]);
}//end for
StdOut.println();
}//end for
min(a);
//StdOut.println(min(a));
}//end main
}
Local minimum of a matrix. Given an N-by-N array a[] of N2 distinct integers, design an algorithm that runs in time proportional to N to find a local minimum: an pair of indices i and j such that a[i][j] < a[i+1][j], a[i][j] < a[i][j+1], a[i][j] < a[i-1][j], and a[i][j] < a[i][j-1] (assuming the neighboring entry is in bounds).
Hint: Find the minimum entry in row N/2, say a[N/2][j]. Check its two vertical neighbors a[N/2-1][j] and a[N/2+1][j]. Recur in the half with the smaller neighbor. In that half, find the minimum entry in column N/2.
答:
public class E1d4d19
{
public static void min(int[][] a)
{
int Rlo=1;
int Rhi=a.length;
int Rmid;
//
int Clo=1;
int Chi=a[0].length;
int Cmid;
while(Rlo<Rhi && Clo<Chi)
{
Rmid=(Rlo+Rhi)/2;
Cmid=(Clo+Chi)/2;
if(a[Rmid-1][Cmid]<a[Rmid][Cmid])
Rhi=Rmid-1;
else if(a[Rmid][Cmid]>a[Rmid+1][Cmid])
Rlo=Rmid+1;
else if(a[Rmid][Cmid-1]<a[Rmid][Cmid])
Chi=Cmid-1;
else if(a[Rmid][Cmid]>a[Rmid][Cmid+1])
Clo=Cmid+1;
else
{
StdOut.printf("row=%d,col=%d",Rmid,Cmid);
return ;
}
}
StdOut.print("can't find");
}
public static void main(String[] args)
{
int N=Integer.parseInt(args[0]);
int[][] a=new int[N][N];
int k=0;
for(int i=0;i<N;i++)
{
for(int j=0;j<N;j++)
{
a[i][j]=StdRandom.uniform(N*N);//数组值会有重复。
StdOut.printf("%6d ",a[i][j]);
}//end for
StdOut.println();
}//end for
min(a);
//StdOut.println(min(a));
}//end main
}