# 如何正确地遍历一个二维数组？

go评论68阅读模式

How to properly navigate through a 2d array?

# 问题

``````import java.io.*;
import java.awt.*;
import java.util.*;

public class toygrid {
static int[][] gridarray = new int[8][8];
static int f = 0;
static int sum = 0;
static String direction = "";

public static void main(String args[]) {
int[][] gridarray = {{ 0,21,20, 5,25,25,35,15},{12,26,43,29,15,26,15,12},
{ 7,18,23,28,36,32,12,18},{43,34,35,18,25,18,21,25},
{32,41,23, 9,21,17,24,14},{12, 9,20,42, 9,19,26,22},
{30,17,17,35,14,25,14,21},{15,21,37,24,19,15,35,15}};

grid(gridarray);
}

static void grid(int[][] gridarray) {
for (int i = 0; i < 7; i++) {
for (int j = 0; j < 7; j++) {
if (i * j == 49) {
break;
} else {
if (gridarray[i][j + 1] < gridarray[i + 1][j]) {
direction += "R";
sum += gridarray[i][j + 1];
j = j + 1;
} else {
direction += "D";
sum += gridarray[i + 1][j];
i = i + 1;
}
}
}
}
System.out.println(direction + " SUM:" + sum);
}
}
``````

So im trying to navigate a toy through a 2d array to get from one corner of the 2d array to the other side of the 2d array. The array is 8x8 and the toy can only turn right and downwards. The grid would look something like this.

0,12,7,43,32,12,30,15

21,26,18,34,41,9,17,21

20,43,23,35,23,20,17,37

5,29,28,18,9,42,35,24,

25,15,36,25,21,9,14,19,

25,26,32,,18,17,19,25,15

35,15,12,21,24,26,14,35,

15,12,18,25,14,22,21,15

Now to get from (0,0) to (8,8). It has to look at the number(which is just the number of seconds in the case of the question) to the right and down and see which one is smaller. Whichever one is smaller it will go that way. Now the question is to find the shortest time to reach (8,8) and it will output the direction it went and the total value at the end.

Sample Output (for the grid provided above):

``````total= 234
direction= RRDDDRRDRRDDDR
``````

I have done most of the code properly, just my total value and directions doesn't match with the sample output. I feel it is a logic error and can't seem to find it. Any help would be appreciated. Here's my code so far.

``````import java.io.*;
import java.awt.*;
import java.util.*;
public class toygrid {
static int[][] gridarray = new int[8][8];
static int f=0;
static int sum=0;
static String direction=&quot;&quot;;
public static void main(String args[]) {
int [][]gridarray = {{ 0,21,20, 5,25,25,35,15},{12,26,43,29,15,26,15,12},
{ 7,18,23,28,36,32,12,18},{43,34,35,18,25,18,21,25},
{32,41,23, 9,21,17,24,14},{12, 9,20,42, 9,19,26,22},
{30,17,17,35,14,25,14,21},{15,21,37,24,19,15,35,15}};
grid(gridarray);
// System.out.println(grid(gridarray));
}
static void grid(int[][] gridarray)
{
for(int i=0; i&lt;7;i++)
{
for(int j=0; j&lt;7;j++)
{
if(i*j==49)
{
break;
}
else
{
if(gridarray[i][j+1] &lt; gridarray[i+1][j])
{
direction +=&quot;R&quot;;
sum +=gridarray[i][j+1];
j=j+1;
}else
{
direction +=&quot;D&quot;;
sum +=gridarray[i+1][j];
i=i+1;
}
}
}
}
System.out.println(direction + &quot; SUM:&quot; +sum );
// System.out.println(gridarray.length);
}
}
``````

Any help would be appreciated thanks!

# 答案1

> 它需要查看右边和下面的数字（在问题的情况下只是秒数），然后确定哪一个较小。无论哪个较小，它都会朝那个方向前进。

``````public static void navigateGrid(int[][] gridarray) {
int yUpperBound = gridarray.length;
int xUpperBound = gridarray[0].length; // 假设所有行具有相同的宽度

int x = 0;
int y = 0;
int sum = 0;
boolean goRight;
String direction = "";
do {
if (x < (xUpperBound - 1) && y < (yUpperBound - 1)) {
// 我们可以向右或向下前进，因此我们必须做出决策
goRight = (gridarray[y][x + 1] < gridarray[y + 1][x]);
} else {
// 我们要么可以向右前进，要么不能；那么我们必须向下前进
goRight = (x < (xUpperBound - 1));
}
if (goRight) {
x++;
direction = direction + "R";
} else {
y++;
direction = direction + "D";
}
sum = sum + gridarray[y][x];
} while (x != (xUpperBound - 1) || y != (yUpperBound - 1));
System.out.println(direction + " SUM:" + sum);
}
``````

``````int [][]gridarray = {{ 0,21,20, 5,25,25,35,15},
{12,26,43,29,15,26,15,12},
{ 7,18,23,28,36,32,12,18},
{43,34,35,18,25,18,21,25},
{32,41,23, 9,21,17,24,14},
{12, 9,20,42, 9,19,26,22},
{30,17,17,35,14,25,14,21},
{15,21,37,24,19,15,35,15}};
``````

> It has to look at the number(which is just the number of seconds in
> the case of the question) to the right and down and see which one is
> smaller. Whichever one is smaller it will go that way.

you don't need `for` loops at all. Just keep an `x` and `y` value to track your current position, then decide whether you should go right or down. You'll also need to track whether you're at the right or bottom edge, in which case you wouldn't make a decision, you'd just move along the appropriate edge until you hit the corner.

So we can use a `do...while` loop until we hit that bottom corner:

``````  public static void navigateGrid(int[][] gridarray)
{
int yUpperBound = gridarray.length;
int xUpperBound = gridarray[0].length; // assume all rows have same width
int x=0;
int y=0;
int sum = 0;
boolean goRight;
String direction = &quot;&quot;;
do {
if (x &lt; (xUpperBound-1) &amp;&amp; y &lt; (yUpperBound-1)) {
// we can go right OR down, so we have to make a decision
goRight = (gridarray[y][x+1] &lt; gridarray[y+1][x]);
}
else {
// we can either go right, or we can&#39;t; then we have to go down
goRight = (x &lt; (xUpperBound-1));
}
if (goRight) {
x++;
direction = direction + &quot;R&quot;;
}
else {
y++;
direction = direction + &quot;D&quot;;
}
sum = sum + gridarray[y][x];
} while (x!=(xUpperBound-1) || y!=(yUpperBound-1));
System.out.println(direction + &quot; SUM:&quot; + sum);
}
``````

Here's the data from your matrix in your CODE (not the description), placed into Excel with the path highlighted that you would take based on your description:

For reference, here's your declaration for the array:

``````int [][]gridarray = {{ 0,21,20, 5,25,25,35,15},{12,26,43,29,15,26,15,12},
{ 7,18,23,28,36,32,12,18},{43,34,35,18,25,18,21,25},
{32,41,23, 9,21,17,24,14},{12, 9,20,42, 9,19,26,22},
{30,17,17,35,14,25,14,21},{15,21,37,24,19,15,35,15}};
``````

# 答案2

``````import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class LabiLab {
// ...（代码部分未翻译）
}

class LabiPath implements Comparable {
// ...（代码部分未翻译）
}
``````

（注意：由于你要求只翻译代码部分，我已经省略了代码中的注释，但代码结构和逻辑保持不变。）

Here is my solution. Best path is 234 weight, [D, D, R, R, R, D, D, R, D, D, R, R, R, D]. Each steps was the values : [0, 12, 7, 18, 23, 28, 18, 9, 21, 9, 14, 25, 14, 21, 15]

As pointed in comments, you can't just "go to the minimum just down or right", if you want the best TOTAL path. (Example, maybe I have 1 down, and 2 right, but if i go down, I'll get a lot of big values after that I would maybe not have if I picked 2 right)

Recursion can be easier for those kind of problem. The most complicated was to store the steps

``````import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class LabiLab {
static int f = 0;
static int sum = 0;
static String direction = &quot;&quot;;
static int[][] gridarray = {
{0, 21, 20, 5, 25, 25, 35, 15},
{12, 26, 43, 29, 15, 26, 15, 12},
{7, 18, 23, 28, 36, 32, 12, 18},
{43, 34, 35, 18, 25, 18, 21, 25},
{32, 41, 23, 9, 21, 17, 24, 14},
{12, 9, 20, 42, 9, 19, 26, 22},
{30, 17, 17, 35, 14, 25, 14, 21},
{15, 21, 37, 24, 19, 15, 35, 15}};
public static void main(String args[]) {
LabiPath bestLabiPath = bestPath(0, 0);
System.out.println(bestLabiPath.steps);
System.out.println(bestLabiPath.distance);
System.out.println(bestLabiPath.distancePerStep);
}
static LabiPath bestPath(int i, int j){
if (i==7 &amp;&amp; j==7) return new LabiPath(gridarray[i][j], Arrays.asList(&quot;X&quot;), Arrays.asList(String.valueOf(gridarray[i][j])));
else if (i == 7) {
LabiPath labiPathToRight = bestPath(i, j + 1).copyWithStepAndDistance(&quot;R&quot;, gridarray[i][j]);
return labiPathToRight;
}
else if (j == 7) {
LabiPath labiPathToDown = bestPath(i + 1, j).copyWithStepAndDistance(&quot;D&quot;, gridarray[i][j]);
return labiPathToDown;
}
else {
LabiPath labiPathToRight = bestPath(i, j + 1).copyWithStepAndDistance(&quot;R&quot;, gridarray[i][j]);
LabiPath labiPathToDown = bestPath(i + 1, j).copyWithStepAndDistance(&quot;D&quot;, gridarray[i][j]);
return labiPathToDown.compareTo(labiPathToRight) &lt; 0 ? labiPathToDown : labiPathToRight;
}
}
}
class LabiPath implements Comparable {
int distance;
List&lt;String&gt; steps ;
List&lt;String&gt; distancePerStep ;
public LabiPath(int distance, List&lt;String&gt; steps, List&lt;String&gt; distancePerStep) {
this.distance = distance;
this.steps = steps;
this.distancePerStep = distancePerStep;
}
public LabiPath copyWithStepAndDistance(String step, int distanceForStep){
int newDistance = this.distance + distanceForStep;
ArrayList&lt;String&gt; stepsCopy = new ArrayList&lt;&gt;(this.steps);
List&lt;String&gt; distancePerStepCopy = new ArrayList&lt;&gt;(this.distanceForStep);
LabiPath newLabiPath = new LabiPath(newDistance, stepsCopy,  distancePerStepCopy);
return newLabiPath;
}
public int compareTo(Object o) {
if (o instanceof LabiPath) {
return distance - ((LabiPath) o).distance;
}
else throw new RuntimeException();
}
}
``````

• 本文由 发表于 2020年10月2日 02:50:37
• 转载请务必保留本文链接：https://go.coder-hub.com/64161570.html
• java

go 110

go 57

go 61

go 66