Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>You need a generic function that work for every direction. That is, to the current position you calculate the position of your neightbors by adding an <code>offsetx</code> and <code>offsety</code> that are in range <code>[-1,1]</code>. Look at this code that do pretty much what you want:</p> <pre><code>//This is your generic-direction function public static boolean check(int row, int col, String word, char[][] puzzle, int offsetx, int offsety) //start with the current position int x = row; int y = col; for (int i = 0; i &lt; word.lenth(); i++){ //Is not equal if (puzzle[x][y] != word.charAt(i)) return false; //Calculate the next position x += offsetx; y += offsety; //check the boundaries, if we go out then we didn't find the word; if (x &lt; 0 || x &gt;= puzzle.length || y &lt; 0 || y &gt;= puzzle[x].length) return false; } return true; } </code></pre> <p>And this is how we call for each direction;</p> <pre><code>//check right if(check(row, col, word, puzzle, 1, 0)) return true; //check left if(check(row, col, word, puzzle, -1, 0)) return true; //check top if(check(row, col, word, puzzle, 0, -1)) return true; ... </code></pre> <p>But an easier way is to define the offset in an array, like this</p> <pre><code>//These are the offset you add to the current position int [] movx ={-1, -1, -1, 0, 0, 1, 1, 1}; int [] movy ={-1, 0, 1, -1, 1, -1, 0, 1}; //this variable will hold if we found or not the string in the puzzle boolean found = false; //check all directions for (int i = 0; i &lt; 8; i++){ //found the string, change the flag 'found' and break if(check(row, col, word, puzzle, movx[i], movy[i])){ found = true; break; } } //string not found if (!found){ System.out.println("String not found"); } </code></pre>
    singulars
    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.
    3. 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