单词搜索程序循环无法终止及网格为空问题排查求助
Let's walk through the critical issues in your code that are causing empty grids and stuck loop behavior in the location method—these fixes should get your program working before your deadline:
1. Fatal Position Calculation Bug
In your location method, you're calculating the column incorrectly:
// Wrong! Both r and c use division int r = pos / cols; int c = pos / cols;
Columns are determined using modulo, not division. Fix it to:
int r = pos / cols; int c = pos % cols; // Correct column calculation
Without this, every position is mapped to the same column as its row, so all boundary checks and placement logic are completely broken.
2. Reversed Boundary Check Logic
Your first loop in location has backwards logic that rejects all valid positions:
// Wrong! Returns 0 if the position is INSIDE the grid if (rr < rows && cc < cols) { return 0; }
You want to return 0 only if the position goes OUTSIDE the grid. Instead, pre-validate the entire word's path upfront (cleaner than looping):
int dirCol = DIRECTIONS[dir][0]; int dirRow = DIRECTIONS[dir][1]; // Calculate the end position of the word int endR = r + dirRow * (word.length() - 1); int endC = c + dirCol * (word.length() - 1); // Reject if any part of the word is out of bounds if (endR < 0 || endR >= rows || endC < 0 || endC >= cols) { return 0; }
3. Broken Overlap Detection & Missing Grid Placement
Your original code doesn't actually write characters to the grid (so it stays empty!), and your overlap count logic is incorrect—it counts any grid position as an overlap, not matching characters. Here's the fixed logic:
// First verify we can place the word (matching characters or empty cells) int overlaps = 0; int currentR = r; int currentC = c; for (int i = 0; i < word.length(); i++) { char gridChar = wordArr.grid[currentR][currentC]; // Assume WordArray has a char[][] grid char wordChar = word.charAt(i); // Reject if cell is occupied by a non-matching character if (gridChar != '\0' && gridChar != wordChar) { // Use '\0' for empty cells return 0; } // Count overlap if characters match if (gridChar == wordChar) { overlaps++; } // Move to next position (skip for last character) if (i < word.length() - 1) { currentR += dirRow; currentC += dirCol; } } // Now write the word to the grid currentR = r; currentC = c; for (int i = 0; i < word.length(); i++) { wordArr.grid[currentR][currentC] = word.charAt(i); if (i < word.length() - 1) { currentR += dirRow; currentC += dirCol; } }
Make sure your WordArray class has a properly initialized char[][] grid = new char[rows][cols]; (filled with '\0' or spaces initially).
4. Additional Quick Fixes
- Initialize
randproperly: Addprivate static Random rand = new Random();to your class—without this, you'll get repeated "random" values that break placement logic. - Check
minWordsvalue: IfminWordsis set higher than the number of valid words you're inputting, the loop will break early and return an empty grid. - Fix
createWordSearchoutput: The lineSystem.out.println("Word search has been created.");will only run if all 100 attempts fail—move it before the return if you want to confirm success, or add a failure message for when no valid grid is generated.
Fixed location Method (Full Version)
public static int location (WordArray wordArr, String word, int dir, int pos) { int r = pos / cols; int c = pos % cols; int dirCol = DIRECTIONS[dir][0]; int dirRow = DIRECTIONS[dir][1]; // Validate entire word fits in grid int endR = r + dirRow * (word.length() - 1); int endC = c + dirCol * (word.length() - 1); if (endR < 0 || endR >= rows || endC < 0 || endC >= cols) { return 0; } // Check if word can be placed (matches existing characters or empty) int overlaps = 0; int currentR = r; int currentC = c; for (int i = 0; i < word.length(); i++) { char gridChar = wordArr.grid[currentR][currentC]; char wordChar = word.charAt(i); if (gridChar != '\0' && gridChar != wordChar) { return 0; } if (gridChar == wordChar) { overlaps++; } if (i < word.length() - 1) { currentR += dirRow; currentC += dirCol; } } // Place the word into the grid currentR = r; currentC = c; for (int i = 0; i < word.length(); i++) { wordArr.grid[currentR][currentC] = word.charAt(i); if (i < word.length() - 1) { currentR += dirRow; currentC += dirCol; } } // Add to solutions with correct end coordinates wordArr.solutions.add(String.format("%-10s (%d,%d)(%d,%d)", word, c, r, endC, endR)); return word.length() - overlaps; }
These changes should resolve the infinite loop issue, correctly place words into the grid, and generate a valid word search puzzle. Good luck hitting your deadline!
内容的提问来源于stack exchange,提问作者Yashvi Shah

