package com. 算法. 递归;
public class 迷宫 {
public static boolean flag;
public static int [ ] [ ] look;
public static boolean [ ] [ ] book;
public static int [ ] [ ] next= { { 0 , 1 } , { 1 , 0 } , { 0 , - 1 } , { - 1 , 0 } } ;
public static void main ( String[ ] args) {
look = new int [ 8 ] [ 7 ] ;
book = new boolean [ 8 ] [ 7 ] ;
for ( int i= 0 ; i< 8 ; i++ ) {
look[ i] [ 0 ] = 1 ;
look[ i] [ 6 ] = 1 ;
}
for ( int i= 0 ; i< 7 ; i++ ) {
look[ 0 ] [ i] = 1 ;
look[ 7 ] [ i] = 1 ;
}
look[ 2 ] [ 1 ] = 1 ;
look[ 2 ] [ 2 ] = 1 ;
look[ 1 ] [ 4 ] = 1 ;
look[ 3 ] [ 3 ] = 1 ;
look[ 1 ] [ 1 ] = 2 ;
System. out. println ( "初始地图为:" ) ;
for ( int [ ] data : look) {
for ( int temp : data) {
System. out. print ( temp+ " " ) ;
}
System. out. println ( ) ;
}
System. out. println ( "找到的路径:" ) ;
dfs ( 1 , 1 ) ;
if ( flag) {
for ( int [ ] data : look) {
for ( int temp : data) {
System. out. print ( temp+ " " ) ;
}
System. out. println ( ) ;
}
}
}
public static void dfs ( int x, int y) {
if ( x== 6 && y== 5 ) {
flag = true ;
look[ x] [ y] = 2 ;
return ;
} else {
for ( int i= 0 ; i< 4 ; i++ ) {
int tx= x+ next[ i] [ 0 ] ;
int ty= y+ next[ i] [ 1 ] ;
if ( ! book[ tx] [ ty] && look[ tx] [ ty] == 0 ) {
look[ tx] [ ty] = 2 ;
book[ tx] [ ty] = true ;
dfs ( tx, ty) ;
if ( flag) {
return ;
}
look[ tx] [ ty] = 0 ;
book[ tx] [ ty] = false ;
}
}
}
}
}
package com. 算法. 递归;
public class 八皇后 {
public static int ans;
public static int [ ] array= new int [ 8 ] ;
public static void main ( String[ ] args) {
huangHou ( 0 ) ;
System. out. println ( "一共有" + ans+ "中放置方法" ) ;
}
public static void huangHou ( int x) {
if ( x== 8 ) {
ans++ ;
return ;
} else {
for ( int i= 0 ; i< 8 ; i++ ) {
array[ x] = i;
if ( ok ( x) ) {
huangHou ( x+ 1 ) ;
}
}
}
}
public static boolean ok ( int n) {
for ( int i= 0 ; i< n; i++ ) {
if ( array[ i] == array[ n] || Math. abs ( n- i) == Math. abs ( array[ i] - array[ n] ) ) {
return false ;
}
}
return true ;
}
}