[英]Find word in a grid of characters
我必須找出給定字符串可以從二維字母網格構建多少次:
為了構建這個詞,我可以從任何地方開始,然后沿 3 個方向之一從一個單元格移動到另一個單元格:
a) same row, next column (right)
b) next row, same column (down)
c) next row, next column (diagonal right and down)
例子:
char[][] grid = {{'a', 'a'}, {'a', 'a'}};
String str = "aa";
output:
5
Explanation:
a) [0,0][0,1]
b) [0,0][1,0]
c) [1,0][1,1]
d) [0,1][1,1]
e) [0,0][1,1]
到目前為止,這是我的代碼:
class Solution {
public boolean exist(char[][] grid, String str) {
int m=grid.length,n=grid[0].length;
boolean[][] visited=new boolean[m][n];
int result = 0;
for (int i=0;i< m;i++){
for (int j=0;j<n;j++){
if (dfs(grid,visited,i,j,0,str)){
result++;
}
}
}
return result;
}
private boolean dfs(char[][] grid, boolean[][] visited, int x, int y, int i, String str){
int m=grid.length,n=grid[0].length;
if (i==str.length()) return true;
if(x<0||x>=m||y<0||y>=n) return false;
if(visited[x][y]) return false;
if(grid[x][y]!=str.charAt(i)) return false;
int[][] dirs={{1,0},{0,1},{1,1}};
visited[x][y]=true;
for (int[] dir: dirs){
int x1=x+dir[0], y1=y+dir[1];
if (dfs(grid, visited, x1, y1, i+1, str)){
return true;
}
}
visited[x][y]=false;
return false;
}
}
對於我上面提到的示例輸入,我能夠得到 2 而不是 5 的結果。
我怎樣才能解決這個問題?
還有其他更好的方法嗎?
從 0,0 開始跨列和向下工作。 創建一個方法boolean check(String word, int startRow, int startCol, int dRow, int dCol)
如果找到從startRow
開始的單詞,它將返回 true, startCol
在找到每個字母后將列遞增 dCol,行dRow
dCol
如果被檢查的字母不匹配或者行或列超出范圍,它可以立即返回false
。 在循環中調用它三次,首先使用dRow = 0
和dCol = 1
,然后將兩者都設置為 1,然后使用dRow = 1
和dCol = 0
。
更好地命名您的方法dfs
不是一個好名字。
這是我的版本,與上面描述的不完全一樣。 我決定返回一個 int 而不是 boolean,這樣我就可以輕松地將結果添加到總數中。 為了簡化示例,我硬編碼了一個字母網格。
public class FindWord {
static char [][] grid = {
{'b','a','d'},
{'o','a','k'},
{'d','a','d'}
};
static final int cols = grid[0].length;
static final int rows = grid.length;
public static void main(String[] args) {
countWords("bad");
countWords("dad");
countWords("oak");
countWords("bod");
countWords("bid");
countWords("aaa");
countWords("aa");
countWords("d");
}
private static void countWords(String word) {
int total = 0;
for (int r = 0; r < rows; r++) {
for (int c = 0; c < cols; c++) {
total += find(word,r,c,0,1) // across
+ find(word,r,c,1,1) // diagonal
+ find(word,r,c,1,0); // down
}
}
System.out.println(total);
}
private static int find(String word, int row, int col, int dRow, int dCol) {
for (char letter : word.toCharArray()) {
if (row >= rows || col >= cols || grid[row][col] != letter)
return 0;
row += dRow;
col += dCol;
}
return 1;
}
}
你可能會注意到這個例子有一個單字母單詞的錯誤。 它將一個字母單詞計數 3 次,因為它認為相同的起始 position 為橫向、對角線和向下。 這很容易解決,條件是只檢查“交叉”情況,如果字長是一個,則不檢查其他兩個。 我將留給您進行調整。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.