在邂逅了完线性结构的数组和队列后, 我们便偶遇了栈这个东东, 他到底是个啥? 就让我们慢慢揭开它的神秘面纱吧~~~
栈的英文为(stack): 又名堆栈,它是一种运算受限的线性表。限定仅在表尾(栈顶)进行插入和删除操作的线性表
入栈图示
出栈图示
栈的应用场景
思路图
代码实现
package ah.sz.tp.algorithm1; /** * 单向循环链表学习 * * @author TimePause * @create 2020-01-11 20:30 */ public class SingleCircleLinkedListDemo { public static void main(String[] args) { SingleCircleLinkedListDemo demo = new SingleCircleLinkedListDemo(); // 创建了内部类, 所以使用这种方式创建内部类对象 SingleCircleLinkedList list = demo.new SingleCircleLinkedList(); // 调用添加方法 list.add(5); // 调用遍历显示方法 //list.showSingleCircleLinkedList(); list.countBoy(1, 2, 5); } /** * 创建单向循环链表类 */ class SingleCircleLinkedList { // 创建第一个节点 private Boy first = null; // 创建临时指针/变量 private Boy curBoy = null; /** * 根据用户输入, 计算小孩出圈的顺序 * * @param startNo 表示从第几个小孩开始数数 * @param countNum 表示数几下 * @param nums 表示圈中最初有多少个小孩 */ public void countBoy(int startNo, int countNum, int nums) { // 1.对参数进行校验 if (startNo < 1 || countNum > nums || startNo > nums) { System.out.println("参数设置有误,请重新设置!!!"); } //创建辅助指针, 帮助小孩节点出圈(循环链表) Boy helper = first; //2. 让辅助变量helper首先指向这个圈的最后一个节点 while (true) { if (helper.getNext() == first) { break; } // 指针后移 helper = helper.getNext(); //or helper.next } //3. 小孩报数前,先让first和helper移动k-1(startNo-1)次=>从指定地方报数 for (int i = 0; i < startNo - 1; i++) { //同时移动first和helper指针 first = first.getNext(); helper = helper.getNext(); } //4.小孩报数时, 让first和helper的指针同时移动m-1(countMun-1),然后出圈 while (true) { if (helper == first) {//说明圈中只剩下一个元素 break; } // 让first和helper的指针同时移动m-1(countMun-1) for (int j = 0; j < countNum - 1; j++) { first = first.getNext(); helper = helper.getNext(); } //这时first要指向的节点, 就是小孩要出圈的节点 System.out.printf("小孩节点%d 要出圈\n", first.getNo()); //5. 将first指向的小孩节点出圈 //思路:结合图知,首先将first移动到要出圈的节点的下一个节点后,让辅助指针去指向下一个节点,这样要出圈的节点就会被GC first = first.getNext(); helper.setNext(first); } System.out.printf("最后留在圈中的小孩的编号为%d \n", first.no); } /** * 添加方法 * * @param num 添加几个节点 */ public void add(int num) { // 对参数进行校验 if (num < 1) { System.out.println("添加节点个数有误,请重新添加~~~"); return; } //使用for循环来创建我们的环形链表 for (int i = 1; i <= num; i++) { //创建下一个节点/子节点 Boy boy = new Boy(i); // 如果添加一个节点 if (i == 1) { //1.将第一个节点boy作为first(相当于其他链表中的头节点) first = boy; //2.将boy下一个节点指向first(形成环) boy.next = first;//也可以写成 boy.setNext(first); 同理,下面都可以 //3. 将指针移动到first(头节点) curBoy = first; } else { // 如果添加1个以上节点 //1. 将辅助变量指向下一个节点boy 2.将boy指向第一个节点(形成环) 3.一阵移动到一下个节点 curBoy.next = boy; boy.next = first; curBoy = boy; } } } /** * 遍历当前的单向循环链表 */ public void showSingleCircleLinkedList() { // 判断链表是否非空 if (first == null) { System.out.println("当前循环链表为空, 无法遍历哦~~~"); return; } // 调用辅助指针完成遍历 curBoy = first; while (true) { System.out.printf("孩子节点的编号%d \n", curBoy.no); System.out.println(curBoy.toString()); if (curBoy.next == first) { break; } curBoy = curBoy.next; } } } /** * 创建Boy类,用于存放节点信息 */ class Boy { //属性设置成私有,如果是内部类,可以直接使用; 如果是外部类,需要通过get(),set()方法, 或将属性设置成public private int no;//编号 private Boy next;//代表指向下一个节点 //带参构造 public Boy(int no) { this.no = no; } public int getNo() { return no; } public Boy getNext() { return next; } public void setNo(int no) { this.no = no; } public void setNext(Boy next) { this.next = next; } } }
逻辑图
实现代码
public class Calculator { public static void main(String[] args) { //根据前面思路,完成表达式的运算 String expression = "7*2*2-5+1-5+3-4"; //如何处理多位数的问题? //创建两个栈,一个数栈,一个符号栈 ArrayStack2 numStack = new ArrayStack2(10); ArrayStack2 operStack = new ArrayStack2(10); //定义需要的相关变量 int index = 0;//用于扫描表达式 int num1 = 0; int num2 = 0; int oper = 0; int res = 0; char ch = ' '; //将每次扫描得到char保存到ch String keepNum = ""; //==>b.用于拼接 多位数 //开始while循环的扫描expression while (true) { //依次得到expression 的每一个字符==>这里只能处理一位数 ch = expression.substring(index, index + 1).charAt(0);//substring处理得到的是一个string类型, 需要使用charAt转换成char类型 //判断ch是什么,然后做相应的处理 if (operStack.isOper(ch)) {//如果是运算符 //判断当前的符号栈是否为空 if (!operStack.isEmpty()) { //如果符号栈有操作符,就进行比较,如果当前的操作符的优先级小于或者等于栈中的操作符,就需要从数栈中pop出两个数, //在从符号栈中pop出一个符号,进行运算,将得到结果,入数栈,然后将当前的操作符入符号栈 if (operStack.priority(ch) <= operStack.priority(operStack.peek())) { num1 = numStack.pop(); num2 = numStack.pop(); oper = operStack.pop(); res = numStack.cal(num1, num2, oper); //把运算的结果入数栈 numStack.push(res); //然后将当前的操作符入符号栈 operStack.push(ch); } else { //如果当前的操作符的优先级大于栈中的操作符, 就直接入符号栈. operStack.push(ch); } } else { //如果为空直接入符号栈.. operStack.push(ch); // 1 + 3 } } else { //如果是数,则直接入数栈 //numStack.push(ch - 48); //? eg: 我们扫描的 "1+3" 中的 '1' 代表的是ascall是49 而不是数字 1 //a.分析思路 //1. 当处理多位数时,不能发现是一个数就立即入栈,因为他可能是多位数 //2. 在处理数,需要向expression的表达式的index 后再看一位,如果是数就进行扫描,如果是符号才入栈 //3. 因此我们需要定义一个变量 字符串,用于拼接 //c.处理多位数 keepNum += ch; //e.如果ch已经是expression的最后一位,就直接入栈 if (index == expression.length() - 1) { numStack.push(Integer.parseInt(keepNum)); } else { //d.判断下一个字符是不是数字,如果是数字,就继续扫描,如果是运算符,则入栈 //注意是看后一位,不是index++ if (operStack.isOper(expression.substring(index + 1, index + 2).charAt(0))) { //如果后一位是运算符,则入栈 keepNum = "1" 或者 "123" numStack.push(Integer.parseInt(keepNum));//将String的substring转换成int类型 //重要的!!!!!!, keepNum清空 keepNum = ""; } } } //让index + 1, 并判断是否扫描到expression最后. index++; if (index >= expression.length()) { break; } } //当表达式扫描完毕,就顺序的从 数栈和符号栈中pop出相应的数和符号,并运行. while (true) { //如果符号栈为空,则计算到最后的结果, 数栈中只有一个数字【结果】 if (operStack.isEmpty()) { break; } num1 = numStack.pop(); num2 = numStack.pop(); oper = operStack.pop(); res = numStack.cal(num1, num2, oper); numStack.push(res);//将运算好的数据入栈 } //将数栈的最后数,pop出,就是结果 int res2 = numStack.pop(); System.out.printf("表达式 %s = %d", expression, res2); } } //先创建一个栈,直接使用前面创建好 //定义一个 ArrayStack2 表示栈, 需要扩展功能 class ArrayStack2 { private int maxSize; // 栈的大小 private int[] stack; // 数组,数组模拟栈,数据就放在该数组 private int top = -1;// top表示栈顶,初始化为-1 //构造器 public ArrayStack2(int maxSize) { this.maxSize = maxSize; stack = new int[this.maxSize]; } //增加一个方法,可以返回当前栈顶的值, 但是不是真正的pop public int peek() { return stack[top]; } //栈满 public boolean isFull() { return top == maxSize - 1; } //栈空 public boolean isEmpty() { return top == -1; } //入栈-push public void push(int value) { //先判断栈是否满 if (isFull()) { System.out.println("栈满"); return; } top++; stack[top] = value; } //出栈-pop, 将栈顶的数据返回 public int pop() { //先判断栈是否空 if (isEmpty()) { //抛出异常 throw new RuntimeException("栈空,没有数据~"); } int value = stack[top]; top--; return value; } //显示栈的情况[遍历栈], 遍历时,需要从栈顶开始显示数据 public void list() { if (isEmpty()) { System.out.println("栈空,没有数据~~"); return; } //需要从栈顶开始显示数据 for (int i = top; i >= 0; i--) { System.out.printf("stack[%d]=%d\n", i, stack[i]); } } //返回运算符的优先级,优先级是程序员来确定, 优先级使用数字表示 //数字越大,则优先级就越高. public int priority(int oper) { if (oper == '*' || oper == '/') { return 1; } else if (oper == '+' || oper == '-') { return 0; } else { return -1; // 假定目前的表达式只有 +, - , * , / } } //判断是不是一个运算符 public boolean isOper(char val) { return val == '+' || val == '-' || val == '*' || val == '/'; } //计算方法 public int cal(int num1, int num2, int oper) { int res = 0; // res 用于存放计算的结果 switch (oper) { case '+': res = num1 + num2; break; case '-': res = num2 - num1;// 注意顺序 break; case '*': res = num1 * num2; break; case '/': res = num2 / num1; break; default: break; } return res; } }
测试结果
前缀表达式的计算机求值
从右至左扫描表达式,遇到数字时,将数字压入堆栈,遇到运算符时,弹出栈顶的两个数,用运算符对它们做相应的计算(栈顶元素 和 次顶元素),并将结果入栈;重复上述过程直到表达式最左端,最后运算得出的值即为表达式的结果
例如: (3+4)×5-6 对应的前缀表达式就是 - × + 3 4 5 6 , 针对前缀表达式求值步骤如下:
中缀转后缀表达式的计算机求值
从左至右扫描表达式,遇到数字时,将数字压入堆栈,遇到运算符时,弹出栈顶的两个数,用运算符对它们做相应的计算(次顶元素 和 栈顶元素),并将结果入栈;重复上述过程直到表达式最右端,最后运算得出的值即为表达式的结果
例如: (3+4)×5-6 对应的后缀表达式就是 3 4 + 5 × 6 - , 针对后缀表达式求值步骤如下:
我们完成一个逆波兰计算器,要求完成如下任务:
中缀转后缀
大家看到,后缀表达式适合计算式进行运算,但是人却不太容易写出来,尤其是表达式很长的情况下,因此在开发中,我们需要利用后缀表达式计算器将中缀表达式转成后缀表达式。
具体步骤如下:
代码实现
package ah.sz.tp.algorithm1.stack; import java.util.ArrayList; import java.util.List; import java.util.Stack; /** *中缀转后缀表达式 * * @author TimePause * @create 2020-01-14 19:07 */ public class PolandNotation { public static void main(String[] args) { //完成将一个中缀表达式转成后缀表达式的功能 //说明 //1. 1+((2+3)×4)-5 => 转成 1 2 3 + 4 × + 5 – //2. 因为直接对str 进行操作,不方便,因此 先将 "1+((2+3)×4)-5" =》 中缀的表达式对应的List // 即 "1+((2+3)×4)-5" => ArrayList [1,+,(,(,2,+,3,),*,4,),-,5] //3. 将得到的中缀表达式对应的List => 后缀表达式对应的List // 即 ArrayList [1,+,(,(,2,+,3,),*,4,),-,5] =》 ArrayList [1,2,3,+,4,*,+,5,–] String expression = "1+((2+3)*4)-5";//注意表达式 List<String> infixExpressionList = toInfixExpressionList(expression); System.out.println("中缀表达式对应的List=" + infixExpressionList); // ArrayList [1,+,(,(,2,+,3,),*,4,),-,5] List<String> suffixExpreesionList = parseSuffixExpreesionList(infixExpressionList); System.out.println("后缀表达式对应的List" + suffixExpreesionList); //ArrayList [1,2,3,+,4,*,+,5,–] System.out.printf("expression=%d", calculate(suffixExpreesionList)); // ? /* //先定义给逆波兰表达式 //(30+4)×5-6 => 30 4 + 5 × 6 - => 164 // 4 * 5 - 8 + 60 + 8 / 2 => 4 5 * 8 - 60 + 8 2 / + //测试 //说明为了方便,逆波兰表达式 的数字和符号使用空格隔开 //String suffixExpression = "30 4 + 5 * 6 -"; String suffixExpression = "4 5 * 8 - 60 + 8 2 / +"; // 76 //思路 //1. 先将 "3 4 + 5 × 6 - " => 放到ArrayList中 //2. 将 ArrayList 传递给一个方法,遍历 ArrayList 配合栈 完成计算 List<String> list = getListString(suffixExpression); System.out.println("rpnList=" + list); int res = calculate(list); System.out.println("计算的结果是=" + res); */ } //即 ArrayList [1,+,(,(,2,+,3,),*,4,),-,5] =》 ArrayList [1,2,3,+,4,*,+,5,–] //方法:将得到的中缀表达式对应的List => 后缀表达式对应的List public static List<String> parseSuffixExpreesionList(List<String> ls) { //定义两个栈 Stack<String> s1 = new Stack<String>(); // 符号栈 //说明:因为s2 这个栈,在整个转换过程中,没有pop操作,而且后面我们还需要逆序输出 //因此比较麻烦,这里我们就不用 Stack<String> 直接使用 List<String> s2 //Stack<String> s2 = new Stack<String>(); // 储存中间结果的栈s2 List<String> s2 = new ArrayList<String>(); // 储存中间结果的Lists2 //遍历ls for(String item: ls) { //如果是一个数,加入s2 if(item.matches("\\d+")) { s2.add(item); } else if (item.equals("(")) { s1.push(item); } else if (item.equals(")")) { //如果是右括号“)”,则依次弹出s1栈顶的运算符,并压入s2,直到遇到左括号为止,此时将这一对括号丢弃 while(!s1.peek().equals("(")) { s2.add(s1.pop()); } s1.pop();//!!! 将 ( 弹出 s1栈, 消除小括号 } else { //当item的优先级小于等于s1栈顶运算符, 将s1栈顶的运算符弹出并加入到s2中,再次转到(4.1)与s1中新的栈顶运算符相比较 //问题:我们缺少一个比较优先级高低的方法 while(s1.size() != 0 && Operation.getValue(s1.peek()) >= Operation.getValue(item) ) { s2.add(s1.pop()); } //还需要将item压入栈 s1.push(item); } } //将s1中剩余的运算符依次弹出并加入s2 while(s1.size() != 0) { s2.add(s1.pop()); } return s2; //注意因为是存放到List, 因此按顺序输出就是对应的后缀表达式对应的List } //方法:将 中缀表达式转成对应的List // s="1+((2+3)×4)-5"; public static List<String> toInfixExpressionList(String s) { //定义一个List,存放中缀表达式 对应的内容 List<String> ls = new ArrayList<String>(); int i = 0; //这时是一个指针,用于遍历 中缀表达式字符串 String str; // 对多位数的拼接 char c; // 每遍历到一个字符,就放入到c do { //如果c是一个非数字,我需要加入到ls if((c=s.charAt(i)) < 48 || (c=s.charAt(i)) > 57) { ls.add("" + c); i++; //i需要后移 } else { //如果是一个数,需要考虑多位数 str = ""; //先将str 置成"" '0'[48]->'9'[57] while(i < s.length() && (c=s.charAt(i)) >= 48 && (c=s.charAt(i)) <= 57) { str += c;//拼接 i++; } ls.add(str); } }while(i < s.length()); return ls;//返回 } //将一个逆波兰表达式, 依次将数据和运算符 放入到 ArrayList中 public static List<String> getListString(String suffixExpression) { //将 suffixExpression 分割 String[] split = suffixExpression.split(" "); List<String> list = new ArrayList<String>(); for(String ele: split) { list.add(ele); } return list; } //完成对逆波兰表达式的运算 /* * 1)从左至右扫描,将3和4压入堆栈; 2)遇到+运算符,因此弹出4和3(4为栈顶元素,3为次顶元素),计算出3+4的值,得7,再将7入栈; 3)将5入栈; 4)接下来是×运算符,因此弹出5和7,计算出7×5=35,将35入栈; 5)将6入栈; 6)最后是-运算符,计算出35-6的值,即29,由此得出最终结果 */ public static int calculate(List<String> ls) { // 创建给栈, 只需要一个栈即可 Stack<String> stack = new Stack<String>(); // 遍历 ls for (String item : ls) { // 这里使用正则表达式来取出数 if (item.matches("\\d+")) { // 匹配的是多位数 // 入栈 stack.push(item); } else { // pop出两个数,并运算, 再入栈 int num2 = Integer.parseInt(stack.pop()); int num1 = Integer.parseInt(stack.pop()); int res = 0; if (item.equals("+")) { res = num1 + num2; } else if (item.equals("-")) { res = num1 - num2; } else if (item.equals("*")) { res = num1 * num2; } else if (item.equals("/")) { res = num1 / num2; } else { throw new RuntimeException("运算符有误"); } //把res 入栈 stack.push("" + res); } } //最后留在stack中的数据是运算结果 return Integer.parseInt(stack.pop()); } } //编写一个类 Operation 可以返回一个运算符 对应的优先级 class Operation { private static int ADD = 1; private static int SUB = 1; private static int MUL = 2; private static int DIV = 2; //写一个方法,返回对应的优先级数字 public static int getValue(String operation) { int result = 0; switch (operation) { case "+": result = ADD; break; case "-": result = SUB; break; case "*": result = MUL; break; case "/": result = DIV; break; default: System.out.println("不存在该运算符" + operation); break; } return result; } }
结果展示
完整版的逆波兰计算器,功能包括
逆波兰计算器完整版考虑的因素较多,下面给出完整版代码供同学们学习,其基本思路和前面一样,也是使用到:中缀表达式转后缀表达式。
public class ReversePolishMultiCalc { /** * 匹配 + - * / ( ) 运算符 */ static final String SYMBOL = "\\+|-|\\*|/|\\(|\\)"; static final String LEFT = "("; static final String RIGHT = ")"; static final String ADD = "+"; static final String MINUS= "-"; static final String TIMES = "*"; static final String DIVISION = "/"; /** * 加減 + - */ static final int LEVEL_01 = 1; /** * 乘除 * / */ static final int LEVEL_02 = 2; /** * 括号 */ static final int LEVEL_HIGH = Integer.MAX_VALUE; static Stack<String> stack = new Stack<>(); static List<String> data = Collections.synchronizedList(new ArrayList<String>()); /** * 去除所有空白符 * @param s * @return */ public static String replaceAllBlank(String s ){ // \\s+ 匹配任何空白字符,包括空格、制表符、换页符等等, 等价于[ \f\n\r\t\v] return s.replaceAll("\\s+",""); } /** * 判断是不是数字 int double long float * @param s * @return */ public static boolean isNumber(String s){ Pattern pattern = Pattern.compile("^[-\\+]?[.\\d]*$"); return pattern.matcher(s).matches(); } /** * 判断是不是运算符 * @param s * @return */ public static boolean isSymbol(String s){ return s.matches(SYMBOL); } /** * 匹配运算等级 * @param s * @return */ public static int calcLevel(String s){ if("+".equals(s) || "-".equals(s)){ return LEVEL_01; } else if("*".equals(s) || "/".equals(s)){ return LEVEL_02; } return LEVEL_HIGH; } /** * 匹配 * @param s * @throws Exception */ public static List<String> doMatch (String s) throws Exception{ if(s == null || "".equals(s.trim())) throw new RuntimeException("data is empty"); if(!isNumber(s.charAt(0)+"")) throw new RuntimeException("data illeagle,start not with a number"); s = replaceAllBlank(s); String each; int start = 0; for (int i = 0; i < s.length(); i++) { if(isSymbol(s.charAt(i)+"")){ each = s.charAt(i)+""; //栈为空,(操作符,或者 操作符优先级大于栈顶优先级 && 操作符优先级不是( )的优先级 及是 ) 不能直接入栈 if(stack.isEmpty() || LEFT.equals(each) || ((calcLevel(each) > calcLevel(stack.peek())) && calcLevel(each) < LEVEL_HIGH)){ stack.push(each); }else if( !stack.isEmpty() && calcLevel(each) <= calcLevel(stack.peek())){ //栈非空,操作符优先级小于等于栈顶优先级时出栈入列,直到栈为空,或者遇到了(,最后操作符入栈 while (!stack.isEmpty() && calcLevel(each) <= calcLevel(stack.peek()) ){ if(calcLevel(stack.peek()) == LEVEL_HIGH){ break; } data.add(stack.pop()); } stack.push(each); }else if(RIGHT.equals(each)){ // ) 操作符,依次出栈入列直到空栈或者遇到了第一个)操作符,此时)出栈 while (!stack.isEmpty() && LEVEL_HIGH >= calcLevel(stack.peek())){ if(LEVEL_HIGH == calcLevel(stack.peek())){ stack.pop(); break; } data.add(stack.pop()); } } start = i ; //前一个运算符的位置 }else if( i == s.length()-1 || isSymbol(s.charAt(i+1)+"") ){ each = start == 0 ? s.substring(start,i+1) : s.substring(start+1,i+1); if(isNumber(each)) { data.add(each); continue; } throw new RuntimeException("data not match number"); } } //如果栈里还有元素,此时元素需要依次出栈入列,可以想象栈里剩下栈顶为/,栈底为+,应该依次出栈入列,可以直接翻转整个stack 添加到队列 Collections.reverse(stack); data.addAll(new ArrayList<>(stack)); System.out.println(data); return data; } /** * 算出结果 * @param list * @return */ public static Double doCalc(List<String> list){ Double d = 0d; if(list == null || list.isEmpty()){ return null; } if (list.size() == 1){ System.out.println(list); d = Double.valueOf(list.get(0)); return d; } ArrayList<String> list1 = new ArrayList<>(); for (int i = 0; i < list.size(); i++) { list1.add(list.get(i)); if(isSymbol(list.get(i))){ Double d1 = doTheMath(list.get(i - 2), list.get(i - 1), list.get(i)); list1.remove(i); list1.remove(i-1); list1.set(i-2,d1+""); list1.addAll(list.subList(i+1,list.size())); break; } } doCalc(list1); return d; } /** * 运算 * @param s1 * @param s2 * @param symbol * @return */ public static Double doTheMath(String s1,String s2,String symbol){ Double result ; switch (symbol){ case ADD : result = Double.valueOf(s1) + Double.valueOf(s2); break; case MINUS : result = Double.valueOf(s1) - Double.valueOf(s2); break; case TIMES : result = Double.valueOf(s1) * Double.valueOf(s2); break; case DIVISION : result = Double.valueOf(s1) / Double.valueOf(s2); break; default : result = null; } return result; } public static void main(String[] args) { //String math = "9+(3-1)*3+10/2"; String math = "12.8 + (2 - 3.55)*4+10/5.0"; try { doCalc(doMatch(math)); } catch (Exception e) { e.printStackTrace(); } } }
运行结果
递归就是方法自己调用自己, 且每次调用时传入不同变量 递归的出现是帮助解决复杂问题, 简化代码
递归代码举例
public static int factorial(int n) { if (n == 1) { return 1; } else { return factorial(n - 1) * n; }}
思路分析
代码实现
/** * 迷宫回溯问题 * * @author TimePause * @create 2020-01-26 21:26 */ public class MiGong { public static void main(String[] args) { // 先创建一个二维数组(8行7列),模拟迷宫 // 地图 int[][] map = new int[8][7]; // 使用1 表示墙 // 上下全部置为1(第0行-第6行的列) for (int i = 0; i < 7; i++) { map[0][i] = 1; map[7][i] = 1; } // 左右全部置为1(第0列-第7列的行) for (int i = 0; i < 8; i++) { map[i][0] = 1; map[i][6] = 1; } //设置挡板, 1 表示 map[3][1] = 1; map[3][2] = 1; // map[1][2] = 1; // map[2][2] = 1; // 输出地图 System.out.println("地图的情况"); for (int i = 0; i < 8; i++) { for (int j = 0; j < 7; j++) { System.out.print(map[i][j] + " "); } System.out.println(); } //使用递归回溯给小球找路 //setWay(map, 1, 1); setWay2(map, 1, 1); //输出新的地图, 小球走过,并标识过的递归 System.out.println("小球走过,并标识过的 地图的情况"); for (int i = 0; i < 8; i++) { for (int j = 0; j < 7; j++) { System.out.print(map[i][j] + " "); } System.out.println(); } } //使用递归回溯来给小球找路 //说明 //1. map 表示地图 //2. i,j 表示从地图的哪个位置开始出发 (1,1) //3. 如果小球能到 map[6][5] 位置,则说明通路找到. //4. 约定: 当map[i][j] 为 0 表示该点没有走过 当为 1 表示墙 ; 2 表示通路可以走 ; 3 表示该点已经走过,但是走不通 //5. 在走迷宫时,需要确定一个策略(方法) 下->右->上->左 , 如果该点走不通,再回溯 /** * * @param map 表示地图 * @param i 从哪个位置开始找 * @param j * @return 如果找到通路,就返回true, 否则返回false */ public static boolean setWay(int[][] map, int i, int j) { if(map[6][5] == 2) { // 通路已经找到ok return true; } else { if(map[i][j] == 0) { //如果当前这个点还没有走过 //按照策略 下->右->上->左 走 map[i][j] = 2; // 假定该点是可以走通. if(setWay(map, i+1, j)) {//向下走 return true; } else if (setWay(map, i, j+1)) { //向右走 return true; } else if (setWay(map, i-1, j)) { //向上 return true; } else if (setWay(map, i, j-1)){ // 向左走 return true; } else { //说明该点是走不通,是死路 map[i][j] = 3; return false; } } else { // 如果map[i][j] != 0 , 可能是 1, 2, 3 return false; } } } //修改找路的策略,改成 上->右->下->左 public static boolean setWay2(int[][] map, int i, int j) { if(map[6][5] == 2) { // 通路已经找到ok return true; } else { if(map[i][j] == 0) { //如果当前这个点还没有走过 //按照策略 上->右->下->左 map[i][j] = 2; // 假定该点是可以走通. if(setWay2(map, i-1, j)) {//向上走 return true; } else if (setWay2(map, i, j+1)) { //向右走 return true; } else if (setWay2(map, i+1, j)) { //向下 return true; } else if (setWay2(map, i, j-1)){ // 向左走 return true; } else { //说明该点是走不通,是死路 map[i][j] = 3; return false; } } else { // 如果map[i][j] != 0 , 可能是 1, 2, 3 return false; } } } }
采取第一种策略(下右上左)
采取第二种策略(上右下左)
8皇后问题, 作为回溯算法的经典案例, 于1848年提出: 在8x8 的国际象棋上摆放着八个皇后, 使其不能相互攻击, 即: 在同一列或同一斜线上, 有多少种摆法.(92)
思路图解
具体思路
实现代码
public class Queue8 { //1.定义一个max表示共有多少个皇后 int max = 8; //2.定义数组array, 保存皇后放置位置的结果,比如 arr = {0 , 4, 7, 5, 2, 6, 1, 3} int[] array = new int[max]; static int count = 0; static int judgeCount = 0; public static void main(String[] args) { //测试一把 , 8皇后是否正确 Queue8 queue8 = new Queue8(); queue8.check(0); System.out.printf("一共有%d解法", count); System.out.printf("一共判断冲突的次数%d次", judgeCount); // 1.5w } //5.编写一个方法,放置第n个皇后 //特别注意: check 是每一次递归时,进入到check中都有 for(int i = 0; i < max; i++),因此会有回溯 private void check(int n) { if(n == max) { //n = 8 , 其实8个皇后就既然放好 print(); return; } //6.依次放入皇后,并判断是否冲突 for(int i = 0; i < max; i++) { //先把当前这个皇后 n , 放到该行的第1列 array[n] = i; //判断当放置第n个皇后到i列时,是否冲突 if(judge(n)) { // 不冲突 //接着放n+1个皇后,即开始递归 check(n+1); // } //如果冲突,就继续执行 array[n] = i; 即将第n个皇后,放置在本行得 后移的一个位置 } } //4.查看当我们放置第n个皇后, 就去检测该皇后是否和前面已经摆放的皇后冲突 /** * * @param n 表示第n个皇后 * @return */ private boolean judge(int n) { judgeCount++; for(int i = 0; i < n; i++) { // 说明 //1. array[i] == array[n] 表示判断 第n个皇后是否和前面的n-1个皇后在同一列 //2*. Math.abs(n-i) == Math.abs(array[n] - array[i]) 表示判断第n个皇后是否和第i皇后是否在同一斜线 // n = 1 放置第 2列 1 n = 1 array[1] = 1 // Math.abs(1-0) == 1 Math.abs(array[n] - array[i]) = Math.abs(1-0) = 1 //3. 判断是否在同一行, 没有必要,n 每次都在递增 if(array[i] == array[n] || Math.abs(n-i) == Math.abs(array[n] - array[i]) ) { return false; } } return true; } //3.写一个方法,可以将皇后摆放的位置输出 private void print() { count++; for (int i = 0; i < array.length; i++) { System.out.print(array[i] + " "); } System.out.println(); } }
本文参与腾讯云自媒体分享计划,欢迎正在阅读的你也加入,一起分享。
我来说两句