# Swift之深度优先搜索和广度优先搜索

### 深度优先搜索基本模型

void dfs(int step)
{

{

}

}

### 栗子一

<pre>
let count:Int = 9
var book:[Int] = Array.init(repeatElement(0, count: count + 1))
var num:[Int] = Array.init(repeatElement(0, count: count + 1))

func dfs(step:Int) {

``````//输出一种排列
if step == (count + 1) {
if ((num[1]*100 + num[2]*10 + num[3] + num[4]*100 + num[5]*10 + num[6]) == (num[7]*100 + num[8]*10 + num[9])) {
print(num)
return
}
}

for i in 1...count {

if book[i] == 0 {  //book[i] = 0 表示i没有使用，1表示已经用过了
num[step] = i
book[i] = 1

dfs(step: step+1) //通过函数的递归来实现
book[i] = 0  //回收
}
}
``````

}

dfs(step: 1)
</pre>

### 栗子二

<pre>
var sumStep:Int = 99999
let maze = [[0,0,1,0],
[0,0,0,0],
[0,0,1,0],
[0,1,0,0],
[0,0,0,1]]
var book = Array.init(repeatElement([0,0,0,0,], count: 5))
let endPoint = (2,3)

func dfs(point: (x:Int,y:Int),step:Int) {

``````if point == endPoint {
if step < sumStep {
sumStep = step
}
return
}

let next = [(0,1),  //向右走
(1,0),  //向下走
(0,-1), //向左走
(-1,0)] //向上走

for index in next.indices {

let newPoint = (point.x + next[index].0,point.y + next[index].1) //新坐标点
if (newPoint.0 < 0) || (newPoint.0 > 3) || (newPoint.1 < 0) || (newPoint.1 > 4) {
continue
}

if (maze[newPoint.1][newPoint.0] == 0) &&  (book[newPoint.1][newPoint.0] == 0){

book[newPoint.1][newPoint.0] = 1
dfs(point: newPoint, step: step + 1)
book[newPoint.1][newPoint.0] = 0
}
}
``````

}

dfs(point: (0,0), step: 0)
print(sumStep) //7
</pre>

### 上面深度优先搜索的栗子二换成广度优先搜索代码如下：

<pre>
let maze = [[0,0,1,0],
[0,0,0,0],
[0,0,1,0],
[0,1,0,0],
[0,0,0,1]]
var book = Array.init(repeatElement([0,0,0,0,], count: 5))
//链表节点
struct note {
var x:Int = 0
var y:Int = 0
var f:Int = 0
var step:Int = 0
}

func bfs(maze:[Array<Int>], startPoint: (x:Int,y:Int),endPoint: (x:Int,y:Int)) -> Int {

``````var que:[note] = Array.init(repeatElement(note(), count: 1000))
var tail = 0

let next = [(0,1),  //向右走
(1,0),  //向下走
(0,-1), //向左走
(-1,0)] //向上走

//往队列插入迷宫入口坐标
que[tail].x = startPoint.x
que[tail].y = startPoint.y
que[tail].f = 0
que[tail].step = 0
tail+=1

var flag = 0 //用来标记是都到达endPoint

for index in next.indices {
if (nextPoint.0 < 0) || (nextPoint.0 > 3) || (nextPoint.1 < 0) || (nextPoint.1 > 4) {
continue
}

if (maze[nextPoint.1][nextPoint.0] == 0) &&  (book[nextPoint.1][nextPoint.0] == 0){
book[nextPoint.1][nextPoint.0] = 1

que[tail].x = nextPoint.0
que[tail].y = nextPoint.1
tail+=1
}

if nextPoint == endPoint {
flag = 1
break;
}
}

if flag == 1 {
break
}