代码随想录-算法训练营day30【回溯算法06:重新安排行程、N皇后、解数独、总结】
·
第七章 回溯算法part06
● 332.重新安排行程
● 51. N皇后
● 37. 解数独
● 总结
详细布置
今天这三道题都非常难,那么这么难的题,为啥一天做三道?
因为 一刷 也不求大家能把这么难的问题解决,所以 大家一刷的时候,就了解一下题目的要求,了解一下解题思路,
不求能直接写出代码,先大概熟悉一下这些题,二刷的时候,随着对回溯算法的深入理解,再去解决如下三题。
大家今天的任务,其实是 对回溯算法章节做一个总结就行。
重点是看 回溯算法总结篇:
https://programmercarl.com/%E5%9B%9E%E6%BA%AF%E6%80%BB%E7%BB%93.html
332.重新安排行程(可跳过)
https://programmercarl.com/0332.%E9%87%8D%E6%96%B0%E5%AE%89%E6%8E%92%E8%A1%8C%E7%A8%8B.html
51. N皇后(可跳过)
https://programmercarl.com/0051.N%E7%9A%87%E5%90%8E.html
视频讲解:https://www.bilibili.com/video/BV1Rd4y1c7Bq
37. 解数独(可跳过)
https://programmercarl.com/0037.%E8%A7%A3%E6%95%B0%E7%8B%AC.html
视频讲解:https://www.bilibili.com/video/BV1TW4y1471V
总结
https://programmercarl.com/%E5%9B%9E%E6%BA%AF%E6%80%BB%E7%BB%93.html
往日任务
● day 1 任务以及具体安排:https://docs.qq.com/doc/DUG9UR2ZUc3BjRUdY
● day 2 任务以及具体安排:https://docs.qq.com/doc/DUGRwWXNOVEpyaVpG
● day 3 任务以及具体安排:https://docs.qq.com/doc/DUGdqYWNYeGhlaVR6
● day 4 任务以及具体安排:https://docs.qq.com/doc/DUFNjYUxYRHRVWklp
● day 5 周日休息
● day 6 任务以及具体安排:https://docs.qq.com/doc/DUEtFSGdreWRuR2p4
● day 7 任务以及具体安排:https://docs.qq.com/doc/DUElCb1NyTVpXa0Jj
● day 8 任务以及具体安排:https://docs.qq.com/doc/DUGdsY2JFaFhDRVZH
● day 9 任务以及具体安排:https://docs.qq.com/doc/DUHVXSnZNaXpVUHN4
● day 10 任务以及具体安排:https://docs.qq.com/doc/DUElqeHh3cndDbW1Q
●day 11 任务以及具体安排:https://docs.qq.com/doc/DUHh6UE5hUUZOZUd0
●day 12 周日休息
●day 13 任务以及具体安排:https://docs.qq.com/doc/DUHNpa3F4b2dMUWJ3
●day 14 任务以及具体安排:https://docs.qq.com/doc/DUHRtdXZZSWFkeGdE
●day 15 任务以及具体安排:https://docs.qq.com/doc/DUHN0ZVJuRmVYeWNv
●day 16 任务以及具体安排:https://docs.qq.com/doc/DUHBQRm1aSWR4T2NK
●day 17 任务以及具体安排:https://docs.qq.com/doc/DUFpXY3hBZkpabWFY
●day 18 任务以及具体安排:https://docs.qq.com/doc/DUFFiVHl3YVlReVlr
●day 19 周日休息
●day 20 任务以及具体安排:https://docs.qq.com/doc/DUGFRU2V6Z1F4alBH
●day 21 任务以及具体安排:https://docs.qq.com/doc/DUHl2SGNvZmxqZm1X
●day 22 任务以及具体安排:https://docs.qq.com/doc/DUHplVUp5YnN1bnBL
●day 23 任务以及具体安排:https://docs.qq.com/doc/DUFBUQmxpQU1pa29C
●day 24 任务以及具体安排:https://docs.qq.com/doc/DUEhsb0pUUm1WT2NP
●day 25 任务以及具体安排:https://docs.qq.com/doc/DUExTYXVzU1BiU2Zl
●day 26 休息
●day 27 任务以及具体安排:https://docs.qq.com/doc/DUElpbnNUR3hIbXlY
●day 28 任务以及具体安排:https://docs.qq.com/doc/DUG1yVHdlWEdNYlhZ
●day 29 任务以及具体安排:https://docs.qq.com/doc/DUHZYbWhwSHRCRmp3
目录
0332_重新安排行程
package com.question.solve.leetcode.programmerCarl2._08_backtrackingAlgorithms;
import java.util.*;
/**
* 332.重新安排行程
*/
public class _0332_重新安排行程 {
}
class Solution0332 {//超时
private LinkedList<String> res;
private LinkedList<String> path = new LinkedList<>();
public List<String> findItinerary(List<List<String>> tickets) {
Collections.sort(tickets, (a, b) -> a.get(1).compareTo(b.get(1)));
path.add("JFK");
boolean[] used = new boolean[tickets.size()];
backTracking((ArrayList) tickets, used);
return res;
}
public boolean backTracking(ArrayList<List<String>> tickets, boolean[] used) {
if (path.size() == tickets.size() + 1) {
res = new LinkedList(path);
return true;
}
for (int i = 0; i < tickets.size(); i++) {
if (!used[i] && tickets.get(i).get(0).equals(path.getLast())) {
path.add(tickets.get(i).get(1));
used[i] = true;
if (backTracking(tickets, used)) {
return true;
}
used[i] = false;
path.removeLast();
}
}
return false;
}
}
class Solution0332_2 {
private Deque<String> res;
private Map<String, Map<String, Integer>> map;
private boolean backTracking(int ticketNum) {
if (res.size() == ticketNum + 1) {
return true;
}
String last = res.getLast();
if (map.containsKey(last)) {//防止出现null
for (Map.Entry<String, Integer> target : map.get(last).entrySet()) {
int count = target.getValue();
if (count > 0) {
res.add(target.getKey());
target.setValue(count - 1);
if (backTracking(ticketNum)) return true;
res.removeLast();
target.setValue(count);
}
}
}
return false;
}
public List<String> findItinerary(List<List<String>> tickets) {
map = new HashMap<String, Map<String, Integer>>();
res = new LinkedList<>();
for (List<String> t : tickets) {
Map<String, Integer> temp;
if (map.containsKey(t.get(0))) {
temp = map.get(t.get(0));
temp.put(t.get(1), temp.getOrDefault(t.get(1), 0) + 1);
} else {
temp = new TreeMap<>();//升序Map
temp.put(t.get(1), 1);
}
map.put(t.get(0), temp);
}
res.add("JFK");
backTracking(tickets.size());
return new ArrayList<>(res);
}
}
/* 该方法是对第二个方法的改进,主要变化在于将某点的所有终点变更为链表的形式,优点在于:
1.添加终点时直接在对应位置添加节点,避免了TreeMap增元素时的频繁调整;
2.同时每次对终点进行增加删除查找时直接通过下标操作,避免hashMap反复计算hash。
*/
class Solution0332_3 {
//key为起点,value是有序的终点的列表
Map<String, LinkedList<String>> ticketMap = new HashMap<>();
LinkedList<String> result = new LinkedList<>();
int total;
public List<String> findItinerary(List<List<String>> tickets) {
total = tickets.size() + 1;
//遍历tickets,存入ticketMap中
for (List<String> ticket : tickets) {
addNew(ticket.get(0), ticket.get(1));
}
deal("JFK");
return result;
}
boolean deal(String currentLocation) {
result.add(currentLocation);
//机票全部用完,找到最小字符路径
if (result.size() == total) {
return true;
}
//当前位置的终点列表
LinkedList<String> targetLocations = ticketMap.get(currentLocation);
//没有从当前位置出发的机票了,说明这条路走不通
if (targetLocations != null && !targetLocations.isEmpty()) {
//终点列表中遍历到的终点
String targetLocation;
//遍历从当前位置出发的机票
for (int i = 0; i < targetLocations.size(); i++) {
targetLocation = targetLocations.get(i);
//删除终点列表中当前的终点
targetLocations.remove(i);
//递归
if (deal(targetLocation)) {
return true;
}
//路线走不通,将机票重新加回去
targetLocations.add(i, targetLocation);
result.removeLast();
}
}
return false;
}
/**
* 在map中按照字典顺序添加新元素
*
* @param start 起点
* @param end 终点
*/
void addNew(String start, String end) {
LinkedList<String> startAllEnd = ticketMap.getOrDefault(start, new LinkedList<>());
if (!startAllEnd.isEmpty()) {
for (int i = 0; i < startAllEnd.size(); i++) {
if (end.compareTo(startAllEnd.get(i)) < 0) {
startAllEnd.add(i, end);
return;
}
}
startAllEnd.add(startAllEnd.size(), end);
} else {
startAllEnd.add(end);
ticketMap.put(start, startAllEnd);
}
}
}
0051_N皇后
package com.question.solve.leetcode.programmerCarl2._08_backtrackingAlgorithms;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class _0051_N皇后 {
}
class Solution0051 {
List<List<String>> res = new ArrayList<>();
public List<List<String>> solveNQueens(int n) {
char[][] chessboard = new char[n][n];
for (char[] c : chessboard) {
Arrays.fill(c, '.');
}
backTrack(n, 0, chessboard);
return res;
}
public void backTrack(int n, int row, char[][] chessboard) {
if (row == n) {
res.add(Array2List(chessboard));
return;
}
for (int col = 0; col < n; ++col) {
if (isValid(row, col, n, chessboard)) {
chessboard[row][col] = 'Q';
backTrack(n, row + 1, chessboard);
chessboard[row][col] = '.';
}
}
}
public List Array2List(char[][] chessboard) {
List<String> list = new ArrayList<>();
for (char[] c : chessboard) {
list.add(String.copyValueOf(c));
}
return list;
}
public boolean isValid(int row, int col, int n, char[][] chessboard) {
//检查列
for (int i = 0; i < row; ++i) {//相当于剪枝
if (chessboard[i][col] == 'Q') {
return false;
}
}
//检查45度对角线
for (int i = row - 1, j = col - 1; i >= 0 && j >= 0; i--, j--) {
if (chessboard[i][j] == 'Q') {
return false;
}
}
//检查135度对角线
for (int i = row - 1, j = col + 1; i >= 0 && j <= n - 1; i--, j++) {
if (chessboard[i][j] == 'Q') {
return false;
}
}
return true;
}
}
//方法2:使用boolean数组表示已经占用的直(斜)线
class Solution0051_2 {
List<List<String>> res = new ArrayList<>();
boolean[] usedCol, usedDiag45, usedDiag135;//boolean数组中的每个元素代表一条直(斜)线
public List<List<String>> solveNQueens(int n) {
usedCol = new boolean[n]; // 列方向的直线条数为 n
usedDiag45 = new boolean[2 * n - 1]; // 45°方向的斜线条数为 2 * n - 1
usedDiag135 = new boolean[2 * n - 1]; // 135°方向的斜线条数为 2 * n - 1
//用于收集结果, 元素的index表示棋盘的row,元素的value代表棋盘的column
int[] board = new int[n];
backTracking(board, n, 0);
return res;
}
private void backTracking(int[] board, int n, int row) {
if (row == n) {
//收集结果
List<String> temp = new ArrayList<>();
for (int i : board) {
char[] str = new char[n];
Arrays.fill(str, '.');
str[i] = 'Q';
temp.add(new String(str));
}
res.add(temp);
return;
}
for (int col = 0; col < n; col++) {
if (usedCol[col] | usedDiag45[row + col] | usedDiag135[row - col + n - 1]) {
continue;
}
board[row] = col;
// 标记该列出现过
usedCol[col] = true;
// 同一45°斜线上元素的row + col为定值, 且各不相同
usedDiag45[row + col] = true;
// 同一135°斜线上元素row - col为定值, 且各不相同
// row - col 值有正有负, 加 n - 1 是为了对齐零点
usedDiag135[row - col + n - 1] = true;
// 递归
backTracking(board, n, row + 1);
usedCol[col] = false;
usedDiag45[row + col] = false;
usedDiag135[row - col + n - 1] = false;
}
}
}
0037_解数独
package com.question.solve.leetcode.programmerCarl2._08_backtrackingAlgorithms;
public class _0037_解数独 {
}
class Solution0037 {
public void solveSudoku(char[][] board) {
solveSudokuHelper(board);
}
private boolean solveSudokuHelper(char[][] board) {
//「一个for循环遍历棋盘的行,一个for循环遍历棋盘的列,
// 一行一列确定下来之后,递归遍历这个位置放9个数字的可能性!」
for (int i = 0; i < 9; i++) { // 遍历行
for (int j = 0; j < 9; j++) { // 遍历列
if (board[i][j] != '.') { // 跳过原始数字
continue;
}
for (char k = '1'; k <= '9'; k++) { // (i, j) 这个位置放k是否合适
if (isValidSudoku(i, j, k, board)) {
board[i][j] = k;
if (solveSudokuHelper(board)) { // 如果找到合适一组立刻返回
return true;
}
board[i][j] = '.';
}
}
// 9个数都试完了,都不行,那么就返回false
return false;
// 因为如果一行一列确定下来了,这里尝试了9个数都不行,说明这个棋盘找不到解决数独问题的解!
// 那么会直接返回, 「这也就是为什么没有终止条件也不会永远填不满棋盘而无限递归下去!」
}
}
// 遍历完没有返回false,说明找到了合适棋盘位置了
return true;
}
/**
* 判断棋盘是否合法有如下三个维度:
* 同行是否重复
* 同列是否重复
* 9宫格里是否重复
*/
private boolean isValidSudoku(int row, int col, char val, char[][] board) {
// 同行是否重复
for (int i = 0; i < 9; i++) {
if (board[row][i] == val) {
return false;
}
}
// 同列是否重复
for (int j = 0; j < 9; j++) {
if (board[j][col] == val) {
return false;
}
}
// 9宫格里是否重复
int startRow = (row / 3) * 3;
int startCol = (col / 3) * 3;
for (int i = startRow; i < startRow + 3; i++) {
for (int j = startCol; j < startCol + 3; j++) {
if (board[i][j] == val) {
return false;
}
}
}
return true;
}
}
总结
难,多看多练。
更多推荐
所有评论(0)