国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 學院 > 開發設計 > 正文

矩陣中的路徑

2019-11-08 02:42:06
字體:
來源:轉載
供稿:網友

題目描述

請設計一個函數,用來判斷在一個矩陣中是否存在一條包含某字符串所有字符的路徑。路徑可以從矩陣中的任意一個格子開始,每一步可以在矩陣中向左,向右,向上,向下移動一個格子。如果一條路徑經過了矩陣中的某一個格子,則該路徑不能再進入該格子。 例如[a b c e s f c s a d e e]是3*4矩陣,其包含字符串”bcced”的路徑,但是矩陣中不包含“abcb”路徑,因為字符串的第一個字符b占據了矩陣中的第一行第二個格子之后,路徑不能再次進入該格子。

算法解析: 利用回溯法,首先在矩陣中任選一個格子作為路徑的起點,假設矩陣中的某個格子的字符為ch并且這個格子將對應與路徑上的第i個字符,如果這個正好是路徑上的第i個字符,那么往周圍相鄰的格子找第i+1個字符,直到找到為止。

代碼如下:

public boolean haspath(char[] matrix, int rows, int cols, char[] str) { if (matrix == null || rows < 1 || cols < 1 || str == null){ return false; } boolean[] visited = new boolean[rows * cols]; int[] pathLength = new int[1]; for (int i = 0; i < rows; i++) { for (int j = 0; j < cols; j++) { if (hasPathCore(matrix, rows, cols, i, j, str, pathLength, visited)){ return true; } } } return false; } public boolean hasPathCore(char[] matrix, int rows, int cols, int row, int col, char[] str, int[] pathLength, boolean[] visited){ if (pathLength[0] == str.length){ return true; } boolean hasPath = false; if (row >= 0 && row < rows && col >= 0 && col < cols && matrix[row * cols + col] == str[pathLength[0]] && !visited[row * cols + col]){ ++ pathLength[0]; visited[row * cols + col] = true; hasPath = hasPathCore(matrix, rows, cols, row, col - 1, str, pathLength, visited) || hasPathCore(matrix, rows, cols, row - 1, col, str, pathLength, visited) || hasPathCore(matrix, rows, cols, row, col + 1, str, pathLength, visited) || hasPathCore(matrix, rows, cols, row + 1, col, str, pathLength, visited); if (!hasPath){ -- pathLength[0]; visited[row * cols + col] = false; } } return hasPath; }
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 咸丰县| 都江堰市| 贵阳市| 青海省| 新津县| 商城县| 仙居县| 吴川市| 临武县| 长武县| 吴堡县| 夏河县| 甘德县| 娄烦县| 南投市| 揭东县| 宁陵县| 黑龙江省| 静安区| 桂平市| 沭阳县| 肃宁县| 乐陵市| 珲春市| 彩票| 永川市| 汽车| 姜堰市| 大渡口区| 兰溪市| 台东市| 东台市| 饶河县| 赤城县| 时尚| 凯里市| 鹤岗市| 仙居县| 二连浩特市| 太保市| 治多县|