Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>If I understand the problem correctly, you can pick every adjacent cell for the next letter, right? In that case, the code below would (I think) solve your problem.</p> <p>I changed the constructor of <code>Map</code>, because it is easier to work with a two-dimensional array of <code>char</code>.</p> <p>The function <code>contains</code> does just what your step 3 described: find the first letter and try searching on from there. The function <code>findRecursively</code> searches for the rest of the word recursively.</p> <pre><code>public class Map { private char[][] board; public Map(final char[] pTab1, final char[] pTab2, final char[] pTab3, final char[] pTab4) { board = new char[4][4]; for (int i = 0 ; i &lt; 4 ; i++) { board[0][i] = pTab1(i); board[1][i] = pTab2(i); board[2][i] = pTab3(i); board[3][i] = pTab4(i); } } public boolean contains(String word) { char[] array = word.toCharArray(); // empty string is trivial if (array.length == 0) return true; for(int i = 0; i &lt; 4; i++) { for (int j = 0; j &lt; 4; j++) { if (board[i][j] == array[0] &amp;&amp; findRecursively(i, j, array, 1)) return true; } } return false; } public boolean isValid(int i, int j) { return (0 &lt;= i &amp;&amp; i &lt; 4) &amp;&amp; (0 &lt;= j &amp;&amp; j &lt; 4); } public boolean findRecursively(int i, int j, char[] array, int index) { // reached end of word if (index == array.length) { return true; } else { // loop over all neighbors for (int di = -1; di &lt;= 1; di++) { for (int dj = -1; dj &lt;= 1; dj++) { // skip cell itself and invalid cells if (!(di == 0 &amp;&amp; dj == 0) &amp;&amp; isValid(i+di, j+dj)) { if (board[i+di][j+dj] == array[index] &amp;&amp; findRecursively(i+di, j+dj, array, index+1)) return true; } } } return false; } } } </code></pre>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload