Last active
December 15, 2018 01:49
-
-
Save willard1218/dd4946d7f1d9c68faaa82b2466a7f9b3 to your computer and use it in GitHub Desktop.
gregre
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// main.swift | |
// ftest | |
// | |
// Created by willard on 2018/12/14. | |
// Copyright © 2018 willard. All rights reserved. | |
// | |
import Foundation | |
print("Hello, World!") | |
struct Point { | |
var x: Int | |
var y: Int | |
} | |
struct Node { | |
var childs:[Node] | |
var point: Point | |
var isPath = false | |
} | |
func vaildPoints(_ p : Point) -> [Point] { | |
return [Point(x: p.x + 2, y: p.y + 1), | |
Point(x: p.x + 1, y: p.y + 2), | |
Point(x: p.x - 2, y: p.y - 1), | |
Point(x: p.x - 1, y: p.y - 2), | |
Point(x: p.x + 2, y: p.y - 1), | |
Point(x: p.x - 2, y: p.y + 1), | |
Point(x: p.x - 1, y: p.y + 2), | |
Point(x: p.x + 1, y: p.y - 2)] | |
.filter{$0.x > 0 && $0.x <= 8 && | |
$0.y > 0 && $0.y <= 8 } | |
} | |
var allPoints = [Point]() | |
func fill( node : inout Node, ep: Point) -> Bool { | |
if node.point.x == ep.x && node.point.y == ep.y { | |
node.isPath = true | |
return true | |
} | |
var childPoints = vaildPoints(node.point) | |
childPoints = childPoints.filter { (point) -> Bool in | |
return !allPoints.contains(where: { (p) -> Bool in | |
return point.x == p.x && point.y == p.y | |
}) | |
} | |
if childPoints.count == 0 { | |
node.isPath = true | |
return false | |
} | |
allPoints += childPoints | |
node.childs = childPoints.map({ (p) -> Node in | |
return Node(childs: [], point: p, isPath: false) | |
}) | |
var hasEnd = false | |
for i in 0...(node.childs.count-1) { | |
hasEnd = hasEnd || fill(node: &node.childs[i], ep: ep) | |
} | |
if (hasEnd) | |
{ | |
node.isPath = true | |
return true | |
} | |
return false | |
} | |
func printResult(node : Node) { | |
print("x : \(node.point.x), y : \(node.point.y) ->") | |
var a = node.childs.filter{$0.isPath == true} | |
for i in a { | |
printResult(node: i) | |
} | |
} | |
let startPoint = Point(x: 1, y: 1) | |
var endPoint = Point(x: 8, y: 8) | |
var node = Node(childs: [], point: startPoint, isPath: true) | |
fill(node: &node, ep: endPoint) | |
printResult(node: node) | |
print("---------") | |
endPoint = Point(x: 1, y: 2) | |
node = Node(childs: [], point: startPoint, isPath: true) | |
fill(node: &node, ep: endPoint) | |
printResult(node: node) | |
print("---------") | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment