130. Surrounded Regions
BFS: 把所有边界上的O先换成A(标记),再深度遍历周围的点。
最后把O换成X(表示不符合要求),所有的A换回O
class Solution { public void solve(char[][] board) { if(board.length == 0 || board[0].length == 0) return; int m = board.length; int n = board[0].length; for(int i = 0; i < m; i++){ dfs(board, i, 0); dfs(board, i, n - 1); } for(int j = 1; j < n - 1; j++){ dfs(board, 0, j); dfs(board, m - 1, j); } for(int i = 0; i < m; i++){ for(int j = 0; j < n; j++){ if(board[i][j] == 'O') board[i][j] = 'X'; if(board[i][j] == 'A') board[i][j] = 'O'; } } } private void dfs(char[][] board, int i, int j){ if(i < 0 || i >= board.length || j < 0 || j >= board[0].length) return; if(board[i][j] == 'X' || board[i][j] == 'A') return; board[i][j] = 'A'; dfs(board, i - 1, j); dfs(board, i + 1, j); dfs(board, i, j - 1); dfs(board, i, j + 1); } }
127. Word Ladder
BFS:queue,使用BFS时必须用到的队列,Set用于放置wordList。按当前
class Solution { public int ladderLength(String beginWord, String endWord, List<String> wordList) { Set<String> set = new HashSet<>(wordList); Queue<String> queue = new LinkedList<>(); queue.add(beginWord); int level = 0; while(!queue.isEmpty()){ int size = queue.size(); for(int i = 0; i < size; i++){ String cur = queue.remove(); char[] wordUnit = cur.toCharArray(); if(cur.equals(endWord)) return level + 1; for(int j = 0; j < cur.length(); j++){ char temp = wordUnit[j]; for(char c = 'a'; c <= 'z'; c++){ wordUnit[j] = c; String s = new String(wordUnit); if(set.contains(s)){ queue.add(s); set.remove(s); } } wordUnit[j] = temp; } } level++; } return 0; } }