public class WordSearch2 { public static void main (String[] argv) { char[][] puzzle = { {'n', 'o', 'h', 't', 'y', 'p', 's'}, {'m', 'i', 'a', 'r', 'y', 'c', 'c'}, {'l', 'l', 'e', 'k', 's', 'a', 'h'}, {'r', 'u', 'b', 'y', 'v', 'm', 'e'}, {'e', 'h', 'h', 'a', 'l', 'l', 'm'}, {'p', 'c', 'j', 'n', 'i', 'c', 'e'}, {'r', 'e', 'e', 'k', 'b', 'i', 'p'} }; findWord (puzzle, "ruby"); } static void findWord (char[][] puzzle, String word) { // First convert the String into a char array. char[] letters = word.toCharArray (); // Now try every possible starting point in the puzzle array. boolean over = false; boolean found = false; for (int i=0; (i<puzzle.length) && (!over); i++) { for (int j=0; (j<puzzle[i].length) && (!over); j++) { // Use (i,j) as the starting point. found = true; // Try to find the given word's letters. for (int k=0; (k<letters.length) && (found); k++) { if ( (j+k >= puzzle[i].length) || (letters[k] != puzzle[i][j+k]) ) { // Not a match. found = false; } } // If we went the whole length of the word, we found it. if (found) { System.out.println ("String " + word + " found in row=" + i + " col=" +j); over = true; } } } if (! found) { System.out.println ("String " + word + " not found"); } } }