自己写的短路
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class shortestWay {
public static void main(String[] args) {
// TODO Auto-generated method stub
String regex="[nNsSwWeE][nNsSwWeE]*";
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String inWay = null;
boolean errFlag = false;
int cntX = 0;
int cntY = 0;
byte[] byteWay = null;
char[] byteWays = null;
StringBuilder shortestWay = new StringBuilder();
while ((inWay == null) || ("".equals(inWay.trim())) || inWay.length() > 50 || errFlag) {
System.out.print("input the way: ");
try {
inWay = br.readLine();
if (inWay.length() > 50)
System.out.println("wrong way length");
Pattern p=Pattern.compile(regex);
Matcher m=p.matcher(inWay);
if(m.matches()){
errFlag = false;
System.out.println("you just input the way is :" + m.group());
}else{
errFlag = true;
System.out.println("wrong way");
}
}
catch (IOException ioe1){
}
}
long start = System.nanoTime();
byteWay = inWay.getBytes();
for (int i = 0; i < byteWay.length; i++) {
if ( ( byteWay[i] == 78 ) || ( byteWay[i] == 110) ) {
cntX += 1;
}
else if (( byteWay[i] == 83 ) || ( byteWay[i] == 115)){
cntX -= 1;
}
else if (( byteWay[i] == 69 ) || ( byteWay[i] == 101)){
cntY += 1;
}
else if (( byteWay[i] == 69 ) || ( byteWay[i] == 101)) {
cntY += 1;
}
else if (( byteWay[i] == 87 ) || ( byteWay[i] == 119)) {
cntY -= 1;
}
}
for (int i = 0; i < Math.abs(cntX); i++) {
if (cntX > 0) {
shortestWay.append("N");
}
else {
shortestWay.append("S");
}
}
for (int i = 0; i < Math.abs(cntY); i++) {
if (cntY > 0) {
shortestWay.append("E");
}
else {
shortestWay.append("W");
}
}
byteWays = String.valueOf(shortestWay).toCharArray();
Arrays.sort(byteWays);
shortestWay.setLength(0);
shortestWay.append(byteWays);
System.out.println("shortestWay is :" + shortestWay);
long end = System.nanoTime();
System.out.println("total cost time :" + (end - start) + "(ns)" + "/" + Float.valueOf(String.valueOf(end - start))/1000000 + "(ms)");
}
}
本博客介绍了一个程序,用于验证用户输入的路径是否符合特定格式,并计算最短路径。程序首先通过正则表达式验证输入路径,确保其长度不超过50个字符且仅包含指定的字母组合。接下来,程序将输入路径转换为字节数组,并根据路径的方向(北、南、东、西)进行计算。最终,程序输出经过排序的最短路径并计算整个过程的时间消耗。
2715

被折叠的 条评论
为什么被折叠?



