1. 程式人生 > 實用技巧 >常用限流策略———漏桶與令牌桶介紹

常用限流策略———漏桶與令牌桶介紹

題目描述:

請設計一個函式,用來判斷在一個矩陣中是否存在一條包含某字串所有字元的路徑。路徑可以從矩陣中的任意一格開始,每一步可以在矩陣中向左、右、上、下移動一格。如果一條路徑經過了矩陣的某一格,那麼該路徑不能再次進入該格子。

例如,在下面的3×4的矩陣中包含一條字串“bfce”的路徑(路徑中的字母用加粗標出)。

[["a","b","c","e"],
 ["s","f","c","s"],
 ["a","d","e","e"]]

但矩陣中不包含字串“abfb”的路徑,因為字串的第一個字元b佔據了矩陣中的第一行第二個格子之後,路徑不能再次進入這個格子。

示例 1:

輸入:board = [["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], word = "ABCCED"
輸出:true

class Solution {

    public static void main(String[] args) {
        Solution solution = new Solution();
        char[][] board = {{'C','A','A'},{'A','A','A'},{'B','C','D'}};
        System.out.println(solution.exist(board,
"AAB")); } public boolean exist(char[][] board, String word) { for (int i = 0; i < board.length; i++) { for (int j = 0; j < board[0].length; j++) { char c = board[i][j]; if (c == word.charAt(0)){ boolean[][] visited = new
boolean[board.length][board[0].length]; boolean out = search(board,visited,word,0,i,j); if (out){ return true; } } } } boolean[][] visited = new boolean[board.length][board[0].length]; boolean out = search(board,visited,word,0,1,1); return false; } private boolean search(char[][] board, boolean[][] visited, String string, int index, int i, int j) { if (string.length() - 1== index){ return true; } visited[i][j] = true; char c = string.charAt(index+1); int upi = i - 1>=0?(i-1):i; int dni = i + 1<board.length?(i + 1):i; int ltj = j - 1>=0?(j-1):j; int rtj = j + 1<board[0].length?(j + 1):j; if (!visited[upi][j] && board[upi][j] == c){ boolean out = search(board, visited, string, index+1, upi, j); if (out) return true; } if (!visited[dni][j] && board[dni][j] == c){ boolean out = search(board, visited, string, index+1, dni, j); if (out) return true; } if (!visited[i][ltj] && board[i][ltj] == c){ boolean out = search(board, visited, string, index+1, i, ltj); if (out) return true; } if (!visited[i][rtj] && board[i][rtj] == c){ boolean out = search(board, visited, string, index+1, i, rtj); if (out) return true; } visited[i][j] = false; return false; } }