/**
* a b c
* d e f
* g h i
* j k l
* 输入 adeh,ehil 则返回true,输入adei,ehik返回false,
*/
public class Arithmetic {
public Boolean nomography(String[][] chars, String param) {
int xlength = chars.length;
int ylength = 0;
if (xlength == 0) {
System.out.println("该二维数组x轴不符合");
} else {
ylength = chars[0].length;
}
//避免有重复key情况,所以用List(list为List<List<String>>)
int initial = 0;
if (xlength * ylength % 16 == 0) {
initial = xlength * ylength / 16;
} else {
initial = xlength * ylength / 16 + 1;
}
//尽量少的减少hashMap的扩容
HashMap<String, List> hashMap = new HashMap<String, List>(16 * initial);
for (int x = 0; x < xlength; x++) {
for (int y = 0; y < ylength; y++) {
//避免出现重复key的情况
List list = hashMap.get(chars[x][y]);
//如果为null,则初始化一个list储存
if (null == list || list.isEmpty()) {
list = new ArrayList<List<String>>();
}
List childList = new ArrayList<String>();
//一定有左节点
if (y != 0) {
childList.add(chars[x][y - 1]);
}
//一定有右节点
if (y != ylength - 1) {
childList.add(chars[x][y + 1]);
}
//一定有上节点
if (x != xlength - 1) {
childList.add(chars[x + 1][y]);
}
//一定有下节点
if (x != 0) {
childList.add(chars[x - 1][y]);
}
list.add(childList);
hashMap.put(chars[x][y], list);
}
}
Boolean result = getResultByList(param, hashMap, 0, param.length());
System.out.println("状态为:" + result);
return result;
}
//通过递归查询当前list是否满足路径搜索可达
private Boolean getResultByList(String param, HashMap<String, List> hashMap, int currentValue, int endValue) {
Boolean ret = false;
List<List<String>> list = hashMap.get(String.valueOf(param.charAt(currentValue)));
//指针需要后移
currentValue++;
//搜寻到最后一个char为结束标志符
if (currentValue == endValue) {
//并且匹配到最后的值则表示搜寻成功
if (list.size() > 0) {
ret = true;
}
} else {
//为空则无法匹配
if (list.isEmpty()) {
return ret;
} else {
for (int i = 0; i < list.size(); i++) {
List<String> strList = list.get(i);
for (int k = 0; k < strList.size(); k++) {
//如果匹配到当前值,则递归继续遍历,直至到达endValue
if (strList.get(k).equals(String.valueOf(param.charAt(currentValue)))) {
ret = getResultByList(param, hashMap, currentValue, endValue);
//如果返回false为无法搜索可达路径,则直接返回
if (!ret) {
return ret;
}
}
}
}
}
}
return ret;
}
}