如何使用Java统计二维字符矩阵中单词的出现次数(仅支持四方向遍历)
Java 实现二维网格单词搜索计数(回溯法)
核心思路
我们采用**回溯+深度优先搜索(DFS)**的方案实现,整体逻辑如下:
- 遍历网格中每一个单元格作为搜索起点,若单元格字符和目标单词首字符匹配,就启动DFS搜索
- 每次DFS仅允许向上下左右四个方向移动,为了避免路径重复,搜索过程中会临时标记已访问的单元格,回溯时恢复原始值
- 当成功匹配到目标单词的最后一个字符时,说明找到1次有效匹配,计入总次数
完整实现代码
public class GridWordCounter { // 上下左右四个方向的偏移量 private static final int[][] DIRS = {{-1,0}, {1,0}, {0,-1}, {0,1}}; public int countWordOccurrences(char[][] grid, String word) { if (grid == null || grid.length == 0 || word == null || word.isEmpty()) { return 0; } int rows = grid.length; int cols = grid[0].length; int count = 0; // 遍历每个单元格作为起点 for (int i = 0; i < rows; i++) { for (int j = 0; j < cols; j++) { if (grid[i][j] == word.charAt(0)) { count += dfs(grid, i, j, word, 0); } } } return count; } private int dfs(char[][] grid, int row, int col, String word, int index) { // 边界判断:坐标越界 / 当前字符不匹配 if (row < 0 || row >= grid.length || col < 0 || col >= grid[0].length || grid[row][col] != word.charAt(index)) { return 0; } // 已经匹配到最后一个字符,计数+1 if (index == word.length() - 1) { return 1; } // 临时标记当前位置为已访问(用特殊字符避免重复走) char temp = grid[row][col]; grid[row][col] = '#'; int total = 0; // 遍历四个方向递归搜索 for (int[] dir : DIRS) { int newRow = row + dir[0]; int newCol = col + dir[1]; total += dfs(grid, newRow, newCol, word, index + 1); } // 回溯:恢复当前位置的原始字符 grid[row][col] = temp; return total; } public static void main(String[] args) { GridWordCounter counter = new GridWordCounter(); // 测试示例1:统计MOBILE char[][] grid1 = { {'M','O','B','S','N'}, {'M','O','I','L','E'}, {'M','B','I','L','E'}, {'O','B','I','L','E'} }; System.out.println(counter.countWordOccurrences(grid1, "MOBILE")); // 输出3 // 测试示例2:统计car char[][] grid2 = { {'c','a','r'}, {'a','r','c'}, {'c','r','a'} }; System.out.println(counter.countWordOccurrences(grid2, "car")); // 输出5 } }
注意事项
- 这里没有额外创建
visited数组记录访问状态,而是直接修改原网格的字符为特殊符号#,搜索完成后回溯恢复,节省了额外的空间开销 - 每次DFS搜索都是独立的,不会影响其他起点的搜索结果,因为每次修改的网格状态都会在回溯时恢复
内容的提问来源于stack exchange,提问作者Tanish
相关产品推荐
相关产品推荐

