我编写了一个类,就叫element吧,又编写了一个链表link,然后以element这个类命名了一个对象position,在每一步改变position的值时候,我都希望把这个崭新的position加进link里面去,就当作栈来用啦~于是用了link.add(position),比如如果position的值每次分别是,1,3,6,8,我就想把1,3,6,8顺序加进link内。但问题来了,因为add(position)是仅仅加进了position这个对象,于是整个链表的值最后都一样,就变成 8,8,8,8了,请问高手有什么方法可以解决这个问题?请给小弟指点迷津~
不能只new 一个position,通过修改position指向的对象的值再把position加进去.这样的话,你加进去的是同一个对象.
上面的link在这里是stack,是编了一个Element类来模拟结构体。关键代码是path()部分。
import java.awt.*;
import java.awt.event.*;import javax.swing.*;
import javax.swing.event.*;
import java.util.*;public class Back extends JPanel {int LEN=30;
int WIT=30;
int NUM=0;
int row;
int col;
int dir;
int[][] map=new int[LEN][WIT];
int [][]=new int[LEN][WIT];
int[][] move={{-1,0},{-1,1},{0,1},{1,1},{1,0},{1,-1},{0,-1},{-1,-1}};
LinkedList<Element> stack=new LinkedList<Element>();
Element position=new Element();public Thread thread;
public Back(){
super();
this.setBackground(Color.white);
creatMap();
path();
thread = new pthread();
thread.start();
}
public void paint(Graphics g){
super.paint(g); paintMap(g);
}
void paintMap(Graphics g ){
g.setColor(Color.red);
int i=0;
for(int wi=0;wi<LEN;wi++)
for(int lg=0;lg<WIT;lg++)
{ if(map[lg][wi]==1&&i<NUM)
{
g.drawRect(3+lg*10, 3+wi*10, 10, 10);
i++;
} } }
void creatMap(){
Random r=new Random();
for(int wi=0;wi<LEN;wi++)
{
this.map[0][wi]=1;
this.map[LEN-1][wi]=1;
}
for(int lg=0;lg<WIT;lg++)
{
this.map[lg][WIT -1]=1;
this.map[lg][0]=1;
}
for(int wi=1;wi<LEN -1;wi++)
for(int lg=1;lg<WIT -1;lg++)
{
this.map[lg][wi]=r.nextInt(1);
}
}
class pthread extends Thread{
public void run(){
while(true)
{
try {
sleep(100);
repaint();
NUM++;
} catch(InterruptedException ire) {
System.err.println("sleep interrupted");
}
}
}
}
class Element{
int row;int col;int dir;
Element()
{row=1;col=1;dir=0;}
}
void path()
{
int row=0;int col=0;int nextr=0;int nextc=0;int found=0;
int dir=0;int i=1; [1][1]=1;
for(int m=0;m<900;m++)
stack.add(position);
System.out.println(stack.get(0));
while(stack.contains(position)&&found==0)
{
position=stack.removeLast();
row=position.row;
col=position.col;
dir=position.dir;
while(dir<8&&found==0)
{
nextr=row+move[dir][0];
nextc=col+move[dir][1];
if(nextr==LEN-2&&nextc==WIT-2)
found=1;
if
(map[nextr][nextc]==0&&[nextr][nextc]==0)
{
[nextr][nextc]=1; position.row=row;
position.col=col; position.dir=++dir;
stack.add(position);
row=nextr;
col=nextc; dir=0;i++;
}
++dir;
}
} }
}
class Element{
int row;int col;int dir;
Element()
{row=1;col=1;dir=0;}
Element(int row,int col,int dir){
this.row=row;
this.col=col;
this.dir=dir;
}
}
position.row=row;
position.col=col;
position.dir=++dir;
stack.add(position);上面的四句用下面的一句替换掉:
stack.add(new Element(row,col,++dir));
#include<stdlib.h>
#include<time.h>
#define MAX 100int [10][10];
int maze[10][10];
void srand(unsigned seed);
//迷宫初始化
void creatmap(int maze[10][10])
{
int lg,wi;
for(wi=0;wi<10;wi++)
{
maze[0][wi]=1;
maze[9][wi]=1;
}
for(lg=0;lg<10;lg++)
{
maze[lg][9]=1;
maze[lg][0]=1;
}
}//随机生成迷宫
void turnmap(int n,int maze[10][10])
{ int i=0,lg,wi;
srand(time(0));
do
{lg=rand()%8;
wi=rand()%8;
if(!maze[lg][wi])
if(lg!=1||wi!=1)
if(lg!=8||wi!=8)
{maze[lg][wi]=1;i++;}
}while(i!=n);
}
//地图输出
void output(int maze[10][10])
{
int lg,wi;
for(lg=0;lg<10;lg++)
for(wi=0;wi<10;wi++)
{
printf("%d ",maze[lg][wi]);
if(wi==9)
printf("\n");
}
} //每一种移动的方向
struct offsets
{
short int vert;
short int horiz;
}move[8]={{-1,0},{-1,1},{0,1},{1,1},{1,0},{1,-1},{0,-1},{-1,-1}};//element包括三个值,行row,列col,方向dir。
struct element
{
short int row;
short int col;
short int dir;
}stack[MAX];//入栈函数
int add(int *top,element item)
{
if(*top>=MAX-1)
{printf("栈满了!");
return -1;
}
stack[++*top]=item;
return 1;
}//出栈函数
element deleted(int *top)
{
if(*top==-1)
{printf("栈到底了!"); }
return stack[(*top)--];
}
//////////////迷宫排查主算法
void path(void)
{
int i,row,col,nextr,nextc,dir,found=0;
element position;
[1][1]=1;int top=0;
stack[0].row=1;stack[0].col=1;stack[0].dir=0;while(top>-1&&!found)
{
position=deleted(&top);
row=position.row;
col=position.col;
dir=position.dir;while(dir<8&&!found)
{
nextr=row+move[dir].vert;
nextc=col+move[dir].horiz;
if(nextr==8&&nextc==8)
found=1;
else if
(!maze[nextr][nextc]&&![nextr][nextc])
{
[nextr][nextc]=1;position.row=row;position.col=col;position.dir=++dir;
add(&top,position);
row=nextr;col=nextc;dir=0;
}
else ++dir;}
}if(found)
{
printf("路径是:\n");
for(i=0;i<=top;i++)
printf("%d %d ",stack[i].row,stack[i].col);
printf("%d %d ",row,col);
printf("8 8 ");
}
else
printf("没有解法!");//
} //////////////////////////////
main()
{
output(maze);
creatmap(maze);
printf("\n");
output(maze);
printf("\n");
int n;
printf("请输入数组中1的数量?\n");
scanf("%d",&n);
turnmap(n,maze);
output(maze);
path();
while(true);
}
import java.util.*;
/** 老鼠走迷宫程序
*
* @author bigbug
* @version 1.0
*//** Direction 方向枚举类型,八个方向。从北方NORTH到西北WESTNORTH按顺时针方向排列*/
enum Direction{
NORTH,
EASTNORTH,
EAST,
EASTSOUTH,
SOUTH,
WESTSOUTH,
WEST,
WESTNORTH
}
/** Maze 迷宫类:
* rows:迷宫的行数。
* columns:迷宫的列数。
* ma:二维字符型数组,其中'1'表示墙,'0'表示通路。在老鼠走迷宫过程中会留下痕迹,'2'表示只路过一次,'3'表示路过二次。
* entranceRow,entranceColumn:分别表示迷宫入口的行、列。
* exitRow,exitColumn:分别表示迷宫出口的行、列。
*/
class Maze{
int rows,columns;
char[][] ma;
int entranceRow=0,entranceColumn=0;
int exitRow=14,exitColumn=14;
/** Maze类的构造方法。
* 其实入口和出口的行、列也应该在构造方法中初始化。
* 但为了省事,在上面的声明中初始化了。
* @param r 表示迷宫的行数。
* @param c 表示迷宫的列数。
*/
Maze(int r,int c){
rows=r;
columns=c;
ma=new char[rows][columns];
try{
//由于2.txt文件的格式,只好用BufferedReader,因为要一行行读出来。
//FileInputStream()方法会抛出FileNotFoundException异常
BufferedReader br=new BufferedReader(new InputStreamReader(new FileInputStream("f:/java/2.txt")));
String s="";
for(int i=0;i<rows;i++){
//readLine()方法会抛出一个IOException异常
s=br.readLine();
for(int j=0;j<columns;j++){
ma[i][j]=s.charAt(j);
}
}
}catch(FileNotFoundException e){
System.out.println("File f:\\java\\2.txt not fount!!");
}catch(IOException ie){
ie.printStackTrace();
}
}//Maze()
/**打印出迷宫示意图,▇表示墙,□表示通路,m表示只通过一次,p表示通过了两次及以上。*/
void printMaze(){
for(int i=0;i<rows;i++){
for(int j=0;j<columns;j++){
if(ma[i][j]=='1'){
System.out.print("▇");
}else if(ma[i][j]=='0'){
System.out.print("□");
}else if(ma[i][j]=='2'){
System.out.print("m ");
}else{
System.out.print("p ");
}
}
System.out.println("");
}
}
}
/** Mouse类
* posRow,posColumn表示老鼠在迷宫的当前位置,即所处的行,列
* direction 老鼠要向那个方向走
* maze 迷宫。
* trace 一个堆栈,存放老鼠走过的地方(迷宫中的行、列),以便走不通时,能退回到上一步路过的位置。
* passable 一个boolean型数组,用以标记迷宫中的某方格mouse是否能走.没有这个数组,程序可能会有死循环。
* 如pasable[i][j]的值为false 表示迷宫中行为i,列为j的方格老鼠不可以走。要么这个格是墙,要么曾经走过。
*/
public class Mouse{
int posRow,posColumn;
Direction direction;
Maze maze;
Stack trace;
boolean[][] passable;
/**Mouse 类的构造方法*/
Mouse(int posRow,int posColumn,Direction d){
this.posRow=posRow;
this.posColumn=posColumn;
direction=d;
maze=new Maze(15,15);
trace=new Stack();
passable=new boolean[maze.rows][maze.columns];
//下面的循环是对passable数组进行初始化,对照迷宫的ma进行,对墙打false标记,通路打true标记
for(int i=0;i<maze.rows;i++){
for(int j=0;j<maze.columns;j++){
if(maze.ma[i][j]=='1'){
passable[i][j]=false;
}else{
passable[i][j]=true;
}
}
}
}
/**探测下一个可以走的位置,并走过去,如果成功返回true,否则返回false*/
boolean getNextPosition(){
//增强型for循环,continue,break也可以用在其中。
//关于枚举类型的应用可以查http://java.sun.com/docs/books/jls/third_edition/html/j3TOC.html。
//这个循环遍历了所有的方向,显然可以优化。可以从当前的方向顺时针转到WESTNORTH。要用到EnumSet类。
for(Direction d:Direction.values()){
//判断下一位置是否超出了迷宫的边界
//对于方向d,老鼠从当前位置朝着d方向走时,行,列的值会变化,变化的值由getRowOffset方法和getColumnOffset方法得到。
if(posRow+getRowOffset(d)<0||posRow+getRowOffset(d)>=maze.rows||posColumn+getColumnOffset(d)<0||posColumn+getColumnOffset(d)>=maze.columns)
continue;
//如果下一位置可以走,就走过去,否则进行下一次循环继续找。
if(!passable[posRow+getRowOffset(d)][posColumn+getColumnOffset(d)]){
continue;
}else{
posRow+=getRowOffset(d);
posColumn+=getColumnOffset(d);
direction=d;
return true;
}
}
//程序能运行到这里,表示上面的return true;没有被执行过,也就是没有找到一个可以走的位置,返回false;
return false;
}
/** 走迷宫
*/
boolean throughMaze(){
trace.push(posRow); //把入口的行值压入栈
trace.push(posColumn); //把入口的列值压入栈
//把入口时老鼠的方向压入栈,在本程序中这个动作没有必要,但 如果要优化getNextPosition()中的for循环,这个动作就是必需的了。
trace.push(direction);
passable[posRow][posColumn]=false; //当值位置标记为不可走。
//当栈不空,且没有到达出口时一直循环。
//栈空表示老鼠退回到了入口。这时表示这个迷宫没有通路到达出口。
while(!trace.empty()&&(posRow!=maze.exitRow||posColumn!=maze.exitColumn)){
if(getNextPosition()){
trace.push(posRow);
trace.push(posColumn);
trace.push(direction);
passable[posRow][posColumn]=false;
maze.ma[posRow][posColumn]='3'; //留下足迹,'3'表示路过多次,这是假设,走完迷宫后再做修正。
}else{ //从当前位置没有找到可以通过的方格时,下面的动作就是退回上一步,以便从那里再找。
//退回上一步,就是出栈,留意出栈的顺序。
direction=(Direction)trace.pop();
posColumn=((Integer)trace.pop()).intValue();
posRow=((Integer)trace.pop()).intValue();
}
}
//退出while循环之后,栈空表示迷宫没有通路。
if(trace.empty()){
return false;
}else{ //栈非空,有通路,栈中存放的就是老鼠只经过一次的那些位置。
//一直出栈,直到栈为空。
while(!trace.empty()){
int r,c;
trace.pop(); //方向出栈,下面用不到方向了,数据扔掉,但动作不可少。
c=((Integer)trace.pop()).intValue();
r=((Integer)trace.pop()).intValue();
maze.ma[r][c]='2'; //把行为r,列为c的方格修正为只经过一次。
}
return true;
}
}
/**返回老鼠当前方格的行值与d方向的方格的行值偏移量
* @param d 方向*/
int getRowOffset(Direction d){
int offset=2;
switch(d){
case NORTH: offset= -1; break;//从当前方格走到北面的方格,行值应该减1.下面类似。
case EASTNORTH: offset= -1; break;
case EAST: offset= 0; break;
case EASTSOUTH: offset= 1; break;
case SOUTH: offset= 1; break;
case WESTSOUTH: offset= 1; break;
case WEST: offset= 0; break;
case WESTNORTH: offset= -1;
}
return offset;
}
/**返回老鼠当前方格的列值与d方向的方格的列值的偏移量*/
int getColumnOffset(Direction d){
int offset=2;
switch(d){
case NORTH: offset= 0; break; //从前方格走到北面的方格,列值不变。下面类似。
case EASTNORTH: offset= 1; break;
case EAST: offset= 1; break;
case EASTSOUTH: offset= 1; break;
case SOUTH: offset= 0; break;
case WESTSOUTH: offset= -1; break;
case WEST: offset= -1; break;
case WESTNORTH: offset= -1;
}
return offset;
}
public static void main(String[] args){
Mouse mouse=new Mouse(0,0,Direction.NORTH);
System.out.println("The maze:");
mouse.maze.printMaze(); //打印初始状态的迷宫
/*试图清除dos窗口的屏幕,不成功。可能执行,cmd是打开一个新的dos窗口,所以cls是清除新窗口的屏幕,而不是当前的。
try{
Runtime.getRuntime().exec("cmd.exe /k cls");
}catch(Exception e){
e.printStackTrace();
}
*/
if(mouse.throughMaze()){
System.out.println("Trace of mouse:");
mouse.maze.printMaze(); //打印经过老鼠践踏后的迷宫:)
System.out.println("m---pass by for once . p----pass by many times ");
}else{
System.out.println("No pass!");
}
}
}
011111111111111
101110011100111
101101110101001
110101000011101
110101011011010
100101011011110
111011101000011
110111001110100
101001011001110
101111011010001
100011101011111
110100101010001
110101011101101
111010100101001
111111111111110
import java.awt.event.*;import javax.swing.*;
import javax.swing.event.*;
import java.util.*;public class Back extends JPanel {int LEN=30;
int WIT=30;
int NUM=0;
int row;
int col;
int dir;
int[][] map=new int[LEN][WIT];
int [][]=new int[LEN][WIT];
int[][] move={{-1,0},{-1,1},{0,1},{1,1},{1,0},{1,-1},{0,-1},{-1,-1}};
LinkedList<Element> stack=new LinkedList<Element>();
LinkedList<Element> allsta=new LinkedList<Element>();
public Thread thread;
public Back(){
super();
this.setBackground(Color.white);
creatMap(200);
boolean r=path();
System.out.println(r);
thread = new pthread();
thread.start();
}
public void paint(Graphics g){
super.paint(g); paintMap(g);
painted(g);
}
void paintMap(Graphics g ){
g.setColor(Color.red);
// int i=0;
for(int wi=0;wi<LEN;wi++)
for(int lg=0;lg<WIT;lg++)
{ if(map[lg][wi]==1)
{
g.drawRect(3+lg*10, 3+wi*10, 10, 10);
// i++;
} } }
void painted(Graphics g){
for(int i=0;i<NUM;i++)
{
if(allsta.get(i).dir==1){
g.setColor(Color.blue);
g.fillRect(3+allsta.get(i).row*10, 3+allsta.get(i).col*10, 10, 10);
}
if(allsta.get(i).dir==0){
g.setColor(Color.white);
g.fillRect(3+allsta.get(i).row*10, 3+allsta.get(i).col*10, 10, 10);
}
}
}
void creatMap(int m){
Random r=new Random();
int i=0;
int l=0;int w=0;
for(int wi=0;wi<LEN;wi++)
{
this.map[0][wi]=1;
this.map[LEN-1][wi]=1;
}
for(int lg=0;lg<WIT;lg++)
{
this.map[lg][WIT -1]=1;
this.map[lg][0]=1;
}
while(i<m){
l=r.nextInt(28)+1;w=r.nextInt(28)+1;
this.map[l][w]=1;i++;
}
}
class pthread extends Thread{
public void run(){
while(true)
{
try {
sleep(100);
repaint();
NUM++;
} catch(InterruptedException ire) {
System.err.println("sleep interrupted");
}
}
}
}
class Element{
int row;int col;int dir;
Element(int row,int col,int dir){
this.row=row;
this.col=col;
this.dir=dir;
}
}
boolean path()
{
int row=0;int col=0;int nextr=0;int nextc=0;int found=0;
int dir=0;int i=1; [1][1]=1;
stack.add(new Element(1,1,0));
allsta.add(new Element(1,1,1));
while(stack.size()!=0&&found==0)/////////////////////////////////////////////////////
{
Element p=stack.removeLast();
row=p.row;
col=p.col;
dir=p.dir;
allsta.add(new Element(row,col,0));
while(dir<8&&found==0)
{
nextr=row+move[dir][0];
nextc=col+move[dir][1];
if(nextr==LEN-2&&nextc==WIT-2)
{stack.add(new Element(row,col,dir));
allsta.add(new Element(row,col,1));
found=1;return true;
}
else if
(map[nextr][nextc]==0&&[nextr][nextc]==0)
{
[nextr][nextc]=1;
stack.add(new Element(row,col,dir++));
allsta.add(new Element(row,col,1));
// System.out.println(stack.get(i).row+" "+stack.get(i).col+" "+stack.get(i).dir);
row=nextr;
col=nextc; dir=0;i++;
}
++dir;
}
} // for(int i1=0;i1<i;i1++)
// System.out.println(stack.get(i1).row+" "+stack.get(i1).col+" "+stack.get(i1).dir);
return false;
}
}
import java.awt.*;
import java.awt.event.*;import javax.swing.*;
import javax.swing.event.*;public class Main extends JFrame{
//JToggleButton[] button=new JToggleButton[3];
//PainterPanel painter=new PainterPanel();
JButton button;
JToolBar toolBar;
Back back;
public Main(){
super("生成迷宫排查");
DrawMap Listener=new DrawMap(); toolBar=new JToolBar();
back=new Back(); button=new JButton("生成迷宫");
button.addActionListener(Listener);
this.add(button);
toolBar.add(button);
Container container=getContentPane();
container.add(toolBar,BorderLayout.NORTH);
container.add(back,BorderLayout.CENTER);
setSize(500,400);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
class DrawMap implements ActionListener{
public void actionPerformed(ActionEvent e){
if (e.getSource()==button){
// System.out.println("11");
}
}
}
public static void main(String[] args){
new Main();
}
}