楊氏矩陣是一個二維矩陣
比如
假設要查找的變量為target
考慮到楊氏矩陣的特性;先給一個比較的基准點;例如 第
再仔細想想
可以考慮以右上角的節點為基准點
基於這種思想;用Java做了如下的實現;
此題可以分為幾種求法
哇
package design;
import java
import java
public class YoungTableau {
private int row;
private int column;
private int value;
public YoungTableau(int x
super();
this
this
this
}
public YoungTableau() {
}
/**
* @param args
*/
public static void main(String args[]) {
int matrix[][] = { {
{
/**
* 測試用例
* target
*/
printMatrix(matrix
find(matrix
find(null
find(matrix
find(matrix
find(matrix
find(matrix
find(matrix
find(matrix
}
/**
* @param matrix
* @param rows
* @param columns
* @return 判斷矩陣輸入合法性
*/
private static boolean isValid(int[][] matrix
boolean isValid = false;
/** 判斷二維矩陣每列合法性 */
if (matrix != null && rows >
int rowLength = matrix
if (columns <= rowLength) {
int columnLength = matrix[
for (int i =
columnLength = columnLength > matrix[i]
: matrix[i]
if (columnLength > columns) {
return isValid;
}
}
isValid = true;
}
} else {
System
}
return isValid;
}
/**
* @param result
*/
public static void printResult(List
System
if (result
System
}
for (YoungTableau yt : result) {
System
+ yt
}
System
}
/**
* @param matrix
* @param rows
* @param columns
* @param target
* @return
*/
public static List
int columns
List
/** 判空及異常的判斷 */
if (isValid(matrix
/** 先以右上角的節點為開始 */
int row =
int column = columns
/** 結束循環的條件 */
while (row < rows && column >=
if (target == matrix[row][column]) {
/** 節點找到
result
matrix[row][column]));
/** 如果找到
column
row++;
} else if (target < matrix[row][column]) {
/** 節點比基准點小
column
} else {
/** 節點比基准點大
row++;
}
}
}
/** 這裡為了方便直接打印一下 */
printResult(result);
return result;
}
/**
* @param source
* @param rows
* @param columns
* 打印矩陣
*/
public static void printMatrix(int[][] matrix
if (isValid(matrix
for (int i =
for (int j =
System
}
System
}
}
}
public void setRow(int row) {
this
}
public int getRow() {
return row;
}
public void setColumn(int column) {
lumn = column;
}
public int getColumn() {
return column;
}
public void setValue(int value) {
this
}
public int getValue() {
return value;
}
}
From:http://tw.wingwit.com/Article/program/Java/hx/201311/25731.html