|
|
Input from file 4 5 pohwp saoaw gnuph suioz |
Input from keyboard snow snowman paw pawn gnu hop hot |
Output p o h w p s a o a w g n u p h s u i o z snow found at 4,1 NE snowman was not found paw found at 3,4 N pawn was not found gnu found at 3,1 E hop found at 1,3 W hot was not found |
You know that there are 4 rows of 5 columns each. The variable numRows contains 4 and the variable numCols contains 5. You want to create an array that has
two more elements in each direction to hold the border.
In this case, it should be 6 rows of 7 columns as shown in the picture.
You would create the array with:
char[ ][ ] puzzle = new char[numRows+2][numCols+2];
Valid indexes for this puzzle are [0][0] up to [5][6] with row first,
then column.
The s with the grey border is at row 2, column 1 or puzzle[2][1].
Finding Words
Suppose you were looking for the first word: snow.
How would you, as a person, look for it?
You try to find the first letter: s.
Looking systematically, you start at row 1 and move across the columns,
then down to row 2 and across those columns.
You would first find an s at
[2][1] (cell with the grey border).
Then you would look in each of the eight possible directions around that s to see if the whole word was there in sequence. When you looked toward the southeast, you have the s at the beginning and an n at puzzle[3][2] to match the second letter. But the next cell in that direction, [4][3], contains i not o. So snow doesn't start at [2][1] going in the southeast direction. You check the other directions and find that snow isn't found in any direction starting there.
You move on to the next s at [4][1] and do the same action of looking around. Looking northeast, you match the s at [4][1] (as it does in every direction), an n at [3][2], an o at [2][3], and a w at [1][4]. You found snow starting at [4][1] going northeast. How did you know you had found it? You were at the end of the word.
Just as we added a border to the puzzle, we placed a null character on the end of the word. (C denotes the end of a string with the null character, and we're mimicking that.)
Note how the row index changed by -1 each time you looked at a letter while the column index changed by 1. Your program would have looked at one more character in the word snow and compared the null at the end of snow to the '=' at [0][5].
Looking for snowman, the last comparison would be between m and the =. How does that differ from finding the complete snow word?
Notice that whenever you are looking for words, if you adjust the indexes to move in a direction, you always run into the border. You won't get an illegal index unless you have border characters in your words. Borders are very helpful in this problem.