2D Arrays: Creation and Access

AP Computer Science A· difficulty 4/5

527 381 469 target = m[0][0]

Consider summing the four orthogonal neighbors of <code>m[r][c]</code> ignoring out-of-bounds:

<code class="language-java">int neigh(int[][] m, int r, int c) { int s = 0; int[] dr = {-1,1,0,0}, dc = {0,0,-1,1}; for (int k = 0; k < 4; k++) { int nr = r + dr[k], nc = c + dc[k]; if (nr >= 0 && nr < m.length && nc >= 0 && nc < m[0].length) s += m[nr][nc]; } return s; } </code></pre> With the highlighted target <code>m[0][0]</code>, what does <code>neigh(m,0,0)</code> return?

  • A

    ArrayIndexOutOfBoundsException

  • B

    5

    check_circle
  • C

    13

  • D

    10

Explanation

Top neighbor (-1,0) and left neighbor (0,-1) are out of bounds and skipped. Down = m[1][0] = 3, right = m[0][1] = 2. Sum = 3 + 2 = 5.

Want 10 more like this — adaptive to your weak spots?

Related questions