7、栈的三个实例

关于迷宫解法的问题,虽然看懂了,但感觉不是最优解。等复习到优先算法时候再来看吧。

  1 package ren.laughing.datastructure.Instance;
  2 
  3 import ren.laughing.datastructure.base.Stack;
  4 import ren.laughing.datastructure.baseImpl.StackLinked;
  5 
  6 /**
  7  * 关于栈的一些实例
  8  * @author Laughing_Lz
  9  * @time 2016年4月7日
 10  */
 11 public class StackInstance {
 12     /**
 13      * 十进制转换为八进制
 14      * 使用Stack倒序输出i%8的余数,即为八进制数
 15      * @param i 十进制数
 16      */
 17     public void baseConversion(int i){
 18         Stack s = new StackLinked();
 19         for(;i>0;i=i/8){
 20             s.push(i%8);
 21         }
 22         while(!s.isEmpty()){
 23             System.out.print(s.pop());
 24         }
 25         System.out.println();
 26     }
 27     /**
 28      * 括号匹配检测{[()]}:
 29      * 此方法仅对括号匹配进行检测,对于运算符号不做检测
 30      * @param str 需要匹配括号的字符串
 31      */
 32     public void bracketmatch(String str){
 33         Stack s = new StackLinked();
 34         for(int i = 0;i<str.length();i++){
 35             char n = str.charAt(i);
 36             if("{[()]}".indexOf((n)) == -1){
 37                 System.out.print(n);
 38             }else if("{([".indexOf(n) != -1){
 39                 s.push(n);
 40                 System.out.print(n);
 41             }else if("})]".indexOf(n) != -1){
 42                 switch (n) {
 43                 case ')':
 44                     if (!s.isEmpty() && s.pop().equals('(')) {
 45                         System.out.print(n);
 46                     } else {
 47                         System.out.print("匹配错误");
 48                         return;
 49                     }
 50                     break;
 51                 case '}':
 52                     if (!s.isEmpty() && s.pop().equals('{')) {
 53                         System.out.print(n);
 54                     } else {
 55                         System.out.print("匹配错误");
 56                         return;
 57                     }
 58                     break;
 59                 case ']':
 60                     if (!s.isEmpty() && s.pop().equals('[')) {
 61                         System.out.print(n);
 62                     } else {
 63                         System.out.print("匹配错误");
 64                         return;
 65                     }
 66                     break;
 67                 default:
 68                     break;
 69                 }
 70             }
 71         }
 72         System.out.println();
 73         if(!s.isEmpty()){
 74             System.out.println("\n匹配错误,左括号多余");
 75         }
 76     }
 77     /**
 78      * 迷宫解法 (类似DFS,深度优先遍历)
 79      * @param maze 迷宫数组
 80      * @param sx 起点x坐标
 81      * @param sy 起点y坐标
 82      * @param ex 终点x坐标
 83      * @param ey 终点y坐标
 84      */
 85     public void mazeExit(char[][] maze,int sx,int sy,int ex,int ey){
 86         Cell[][] cells = creatMaze(maze);//创建迷宫
 87         System.out.println("起点为("+sx+","+sy+"),终点为("+ex+","+ey+"),迷宫图:");
 88         printMaze(cells);//打印迷宫
 89         Stack s = new StackLinked();//定义堆栈
 90         Cell startCell = cells[sx][sy];//起点
 91         Cell endCell = cells[ex][ey];//终点
 92         s.push(startCell);//起点入栈
 93         startCell.visited = true;//标记起点被
 94         while(!s.isEmpty()){//while判断
 95             int x = ((Cell)s.peek()).x;
 96             int y = ((Cell)s.peek()).y;
 97             if(s.peek()!=endCell){//如果不是终点
 98                 int count = 0;
 99                 //走法:遍历下、右、上、左是否访问,若没访问且不是墙,则访问
100                 if (cells[x + 1][y].c == '0' && !cells[x + 1][y].visited) {//
101                     s.push(cells[x + 1][y]);
102                     cells[x + 1][y].visited = true;
103                     count++;
104                 }  if (cells[x][y + 1].c == '0' && !cells[x][y + 1].visited) {//
105                     s.push(cells[x][y + 1]);
106                     cells[x][y + 1].visited = true;
107                     count++;
108                 }  if (cells[x - 1][y].c == '0' && !cells[x - 1][y].visited) {//
109                     s.push(cells[x - 1][y]);
110                     cells[x - 1][y].visited = true;
111                     count++;
112                 }  if (cells[x][y - 1].c == '0' && !cells[x][y - 1].visited) {//
113                     s.push(cells[x][y - 1]);
114                     cells[x][y - 1].visited = true;
115                     count++;
116                 } 
117                 if(count == 0){
118                     s.pop();//都没有,就要回退,出栈
119                 }
120             }else{//如果已经到终点,开始回退打印路线
121                 while(!s.isEmpty()){
122                     Cell cell = (Cell) s.peek();
123                     cell.c = '*';
124                     s.pop();
125                     while(!s.isEmpty()&&!isAjoinCell((Cell)s.peek(),cell)){//★将回退的单元与上一单元比较是否相邻,若不相邻,直接出栈而不标记为路径
126                         s.pop();
127                     }
128                     
129                 }
130                 System.out.println("开始打印路线");
131                 printMaze(cells);
132                 return ;
133             }
134         }
135     }
136     /**
137      * 判断两个单元是否相邻
138      * @param cell1 回退后的单元
139      * @param cell2 上一单元
140      * @return
141      */
142     private boolean isAjoinCell(Cell cell1, Cell cell2) {
143         if (cell1.x == cell2.x && Math.abs(cell1.y - cell2.y) < 2)
144             return true;
145         if (cell1.y == cell2.y && Math.abs(cell1.x - cell2.x) < 2)
146             return true;
147         return false;
148     }
149     /**
150      * 打印迷宫
151      * @param cells
152      */
153     private void printMaze(Cell[][] cells) {
154         for(int i = 0;i<cells.length;i++){
155             for(int j = 0;j<cells[i].length;j++){
156                 System.out.print(cells[i][j].c+" ");
157             }
158             System.out.println();
159         }
160     }
161     /**
162      * 创建迷宫
163      * @param maze
164      * @return
165      */
166     private Cell[][] creatMaze(char[][] maze) {
167         Cell[][] cells = new Cell[maze.length][];
168         for(int i = 0;i<maze.length;i++){
169             cells[i] = new Cell[maze[i].length];//★定义数组y的长度
170             for(int j = 0;j<maze[i].length;j++){
171                 cells[i][j] = new Cell(i, j, false, maze[i][j]);
172 //                cells[i][j].c = maze[i][j];//定义是墙/路/路径
173 //                cells[i][j].visited = false;//初始均未访问
174             }
175         }
176         return cells;
177     }
178     
179     public static void main(String[] args) {
180         StackInstance si =new StackInstance();
181         System.out.println("1、10进制转换为8进制:");
182         si.baseConversion(800);//1440
183         System.out.println("2、括号匹配检测");
184         si.bracketmatch("(12+{34*(32-54)/[76*(32-99)]})+55");
185         System.out.println("3、迷宫解法");
186         char[][] maze1 = { { '1', '1', '1', '1', '1', '1', '1', '1' }, { '1', '0', '1', '1', '0', '1', '1', '1' },
187                 { '1', '0', '0', '0', '0', '1', '0', '1' }, { '1', '1', '1', '0', '0', '0', '0', '1' },
188                 { '1', '0', '0', '0', '0', '0', '0', '1' }, { '1', '0', '0', '0', '0', '0', '0', '1' },
189                 { '1', '1', '0', '0', '0', '0', '0', '1' }, { '1', '1', '1', '1', '1', '1', '1', '1' } };
190         char[][] maze2 ={{'1','1','1','1','1'},{'1','0','1','0','1'},{'1','0','0','0','1'},{'1','0','1','0','1'},{'1','1','1','1','1'}};
191         si.mazeExit(maze1, 4, 1, 1, 1);    
192         si.mazeExit(maze2, 3, 1, 1, 1);
193     }
194     /**
195      * 迷宫单元定义
196      * @author Laughing_Lz
197      * @time 2016年4月12日
198      */
199     class Cell{
200         int x = 0;//x坐标
201         int y = 0;//y坐标
202         boolean visited = false;//是否被访问
203         char c = '0';//'1'是墙,'0'是路,'*'是路径 (初始为0,无意义?)
204         public Cell(int x, int y, boolean visited, char c) {
205             this.x = x;
206             this.y = y;
207             this.visited = visited;
208             this.c = c;
209         }
210         
211     }
212 }

 

posted @ 2016-04-12 16:32  回看欧洲  阅读(258)  评论(0编辑  收藏  举报