我应该如何重新配置箭头"->"以便在完成路径后不打印?



我试图创建一个最佳路径来收集尽可能多的1,但在我执行我的代码后,我仍然有一个箭头指向什么,因为没有更多的地方去。如何删除代码末尾的箭头?

import java.util.Arrays;
import java.util.Scanner;
public class Main{
public static void main(String[] args){
Scanner s1 = new Scanner(System.in);
int n = s1.nextInt();
int m = s1.nextInt();
int mat[][] = new int[n][m];
for (int i = 0; i < mat.length; i++){
for (int j = 0; j < mat[0].length; j++){
mat[i][j] = s1.nextInt();
} 
}
int path[][] = new int[n][m];
for (int i = 0; i < path.length; i++){
Arrays.fill(path[i], -1);
}

int maxCoins = util(0, 0, mat, path);
System.out.println("Max coins:" + maxCoins);

int row = 0, column = 0;
System.out.print("Path:");

while(row < mat.length && column < mat[0].length){
System.out.print("(" + (row + 1) + "," + (column + 1) + ")");
System.out.print("->");

if(row < n - 1 && column < m - 1){
int down = path[row + 1][column];
int right = path[row][column + 1];
if(down > right){
row += 1;
continue;
}
else if (right > down){
column += 1;
continue;
}
else{
row += 1;
continue;
}
}
if(row + 1 < n){
row += 1;
}
else{
column += 1;
}
}
}

private static int util(int row,int column,int mat[][], int path[][]){
if(row >= mat.length || column >= mat[0].length){
return 0;
}

if(path[row][column]!= -1){
return path[row][column];
}

int right = util(row, column + 1, mat,path);
int down = util(row + 1, column, mat,path);

path[row][column]=Math.max(right, down);
if(mat[row][column] == 1){
path[row][column] += 1;
}

return path[row][column];
}
}

我当前的输入看起来像:

5 6
0 0 0 0 1 0
0 1 0 1 0 0
0 0 0 1 0 1
0 0 1 0 0 1
1 0 0 0 1 0

输出为:

Max coins:5
Path:(1,1)->(2,1)->(2,2)->(2,3)->(2,4)->(3,4)->(3,5)->(3,6)->(4,6)->(5,6)->

我只是想删除一个在结束,但不确定在哪里插入我的代码:

System.out.print("->");

最干净的方法是使用StringJoiner。你可以这样使用

StringJoiner joiner = new StringJoiner("->");
joiner.add("a");
joiner.add("b");
System.out.println(joiner); //prints a->b - you can use toString if you want to return a joined String

您还可以为您的连接字符串定义前缀和后缀。

或者如果你熟悉Streams,有Collectors.joining("->")可用。

我想到了三个解决方案:

  1. 在循环中添加另一个检查,并将sysout ->的东西放在该检查之后。
  2. 通常代码会生成一些关于结果的列表或类似的数据并返回它。打印列表要简单得多,因为你知道长度等。
  3. 另一个常见的解决方案是使用StringBuilder并在使用toString()
  4. 生成输出之前对其进行校正。

你可以这样做:

if (!(row == mat.length - 1 && column == mat[0].length - 1)) {
System.out.print("->");
}

或者更简洁一点:

if (arrowIsNotAtTheEnd(mat, row, column)) {
System.out.print("->");
}
// ...
private static boolean arrowIsNotAtTheEnd(int[][] mat, int row, int column) {
return !(row == mat.length - 1 && column == mat[0].length - 1);
}

对于java 8及以上版本,String类已经有了一个方便的连接方法。

CharSequence[] path=new CharSequence[]{
"(1,1)","(2,1)","(2,2)","(2,3)","(2,4)","(3,4)","(3,5)","(3,6)","(4,6)","(5,6)"};
String output=String.join("->",path);
System.out.println(output);
//output: (1,1)->(2,1)->(2,2)->(2,3)->(2,4)->(3,4)->(3,5)->(3,6)->(4,6)->(5,6)

最新更新