-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGridPath.java
More file actions
77 lines (64 loc) · 2.1 KB
/
GridPath.java
File metadata and controls
77 lines (64 loc) · 2.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
public class GridPath {
/**
* Initialized in the constructor with distinct values that never change
*/
private int[][] grid;
private int colMax;
private int rowMax;
public GridPath(int[][] values)
{
grid = values;
colMax = grid[0].length-1;
rowMax = grid.length-1;
}
/**
* Returns the Location representing a neighbor of the grid element at row and col,
* as described in part (a)
* Preconditions: row is a valid row index and col is a valid column index in grid.
* row and col do not specify the element in the last row and last column of grid.
*/
public Location getNextLoc(int row, int col) {
/* to be implemented in part (a) */
Location start = new Location(row, col);
Location toRight = new Location(row, col+1);
Location toBottom = new Location(row+1, col);
if(row == rowMax && col == colMax)
{
return start;
}
else if (col == colMax){
return toBottom;
}
else if (row == rowMax)
{
return toRight;
}
else if (grid[toRight.getRow()][toRight.getCol()] < grid[toBottom.getRow()][toBottom.getCol()]){
return toRight;
}
else
{
return toBottom;
}
}
/**
* Computes and returns the sum of all values on a path through grid, as described in
* part (b)
* Preconditions: row is a valid row index and col is a valid column index in grid.
* row and col do not specify the element in the last row and last column of grid.
*/
public int sumPath(int row, int col) {
/* to be implemented in part (b) */
int sum = grid[row][col];
int nextRowVal = row;
int nextColVal = col;
while (!(nextRowVal == rowMax) && !(nextRowVal == colMax))
{
Location nextPos = getNextLoc(nextRowVal, nextColVal);
nextRowVal = nextPos.getRow();
nextColVal = nextPos.getCol();
sum += grid[nextRowVal][nextColVal];
}
return sum;
}
}