八皇后问题
package com.od202305;
import java.util.Arrays;
/**
* 八皇后问题-回溯法
* 八皇后问题是指在一个 8x8 的棋盘上放置 8 个皇后,要求任意两个皇后都不能处于同一行、同一列或同一对角线上。
*/
public class Od004 {
public static void main(String[] args) {
int n = 8;
int[] queens = new int[n];
solve(queens, 0);
}
private static void solve(int[] queens, int row) {
if (row == queens.length) {
// 找到了一个解
System.out.println(Arrays.toString(queens));
return;
}
for (int col = 0; col < queens.length; col++) {
if (isValid(queens, row, col)) {
queens[row] = col;
solve(queens, row + 1);
}
}
}
private static boolean isValid(int[] queens, int row, int col) {
for (int i = 0; i < row; i++) {
if (queens[i] == col || Math.abs(row - i) == Math.abs(col - queens[i])) {
return false;
}
}
return true;
}
}
单词倒叙
描述

实例与思路

package com.od202305;
/**
* 单词倒叙
*/
public class Od005 {
public static void main(String[] args) {
System.out.println(reverse("woh era uoy ?|ma enif."));
}
public static String reverse(String s1) {
StringBuilder temp = new StringBuilder("");
String resu = "";
for (int i = 0; i < s1.length(); i++) {
//1.判断是否是字母
char c = s1.charAt(i);
if (Character.isLetter(c)) {
temp.append(c);
} else if ("".equals(c)) {
//遇到空格进行反转
StringBuilder reverse = temp.reverse();
reverse.append(" ");
resu += reverse.toString();
temp = new StringBuilder("");
} else {
//遇到符号前者反转
StringBuilder reverse = temp.reverse();
reverse.append(c);
resu += reverse.toString();
temp = new StringBuilder("");
}
}
return resu;
}
}
打印文件
描述

实例与思路

package com.od202305;
import java.util.*;
/**
* 打印文件
*/
public class Demo006 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
sc.nextLine();
/**
* 将打印任务放在 map 对象中
* key: String 打印机编号
* value: List<int[]>数组集合
* int[0]: 优先级
* int[1]: 打印编号
*/
Map<String, List<int[]>> map = new HashMap<>();
int count = 0; //打印编号
for (int i = 0; i < n; i++) {
String[] strs = sc.nextLine().split(" ");
if (strs[0].equals("IN")) { //打印任务
int[] inInts = new int[2];
inInts[0] = Integer.parseInt(strs[2]); //优先级
inInts[1] = ++count; //打印编号递增
List<int[]> inList = new ArrayList<>();
if (map.containsKey(strs[1])) {
inList = map.get(strs[1]);
inList.add(inInts);
} else {
inList.add(inInts);
}
map.put(strs[1], inList);
} else if (strs[0].equals("OUT")) { //进行打印
if (!map.containsKey(strs[1])) { //打印机不存在
System.out.println("NULL");
continue;
}
List<int[]> outList = map.get(strs[1]); //获取 strs[1]打印机的所有任务
if (outList.size() == 0) { //打印机没有任务
System.out.println("NULL");
} else {
outList.sort((a, b) -> { //根据打印优先级排序
return b[0] - a[0];
});
System.out.println(outList.get(0)[1]);
outList.remove(0);
}
}
}
}
}