1. 第一题:走迷宫 门 ABCDE 锁abcde 墙X .路
import java.util.*;
public class Main1 {
public static void dfs(char map[][], int i, int j)
{
if(i < 0 || i >= map.length || j < 0 || j >= map[0].length || map[i][j] == 'X' || map[i][j] == '*')
{
return;
}
map[i][j] = '*';
dfs(map, i + 1, j);
dfs(map, i - 1, j);
dfs(map, i, j + 1);
dfs(map, i, j - 1);
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
while(sc.hasNextInt())
{
int n = sc.nextInt();
int m = sc.nextInt();
if(n == 0 && m == 0)
{
return;
}
char map[][] = new char[n][m];
int start_x = -1;
int start_y = -1;
int end_x = -1;
int end_y = -1;
for(int i = 0; i < n; i++)
{
String temp = sc.next();
for(int j = 0; j < m; j++)
{
map[i][j] = temp.charAt(j);
if(map[i][j] == 'S')
{
start_x = i;
start_y = j;
}
if(map[i][j] == 'G')
{
end_x = i;
end_y = j;
}
}
}
dfs(map, start_x, start_y);
if(map[end_x][end_y] == '*')
{
System.out.println("YES");
}
else
{
System.out.println("NO");
}
}
}
}
2. 第二题:某点到 多边形 每条边的最短距离
import java.util.*;
public class Main2 {
public static class Point
{
double x;
double y;
public Point setPoint(Point point)
{
this.x = point.getX();
this.y = point.getY();
return this;
}
public Point()
{
}
public Point(Float[] point)
{
this.x = point[0];
this.y = point[1];
}
public Point(Double[] point)
{
this.x = point[0];
this.y = point[1];
}
public Point(double x, double y)
{
this.x = x;
this.y = y;
}
public double getX()
{
return x;
}
public void setX(double x)
{
this.x = x;
}
public double getY()
{
return y;
}
public void setY(double y)
{
this.y = y;
}
}
public static double pointToLineDist(Point p, Point a, Point b)
{
double ABx = b.x - a.x;
double ABy = b.y - a.y;
double APx = p.x - a.x;
double APy = p.y - a.y;
double AB_AP = ABx * APx + ABy * APy;
double distAB2 = ABx * ABx + ABy * ABy;
double Dx = a.x, Dy = a.y;
if(distAB2 != 0)
{
double t = AB_AP / distAB2;
if(t >= 1)
{
Dx = b.x;
Dy = b.y;
}
else if(t > 0)
{
Dx = a.x + ABx * t;
Dy = a.y + ABy * t;
}
else
{
Dx = a.x;
Dy = a.y;
}
}
double PDx = Dx - p.x, PDy = Dy - p.y;
return Math.sqrt(PDx * PDx + PDy * PDy);
}
public static double pintoToPolygonMinDist(Point point, List<Point> points)
{
double dist = Double.MAX_VALUE;
int N = points.size();
for(int i = 0, j = N - 1; i < N; j = i++)
{
dist = Math.min(dist, pointToLineDist(point, points.get(i), points.get(j)));
}
return dist;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
Double Ax = sc.nextDouble();
Double Ay = sc.nextDouble();
Point p = new Point();
p.x = Ax;
p.y = Ay;
int n = sc.nextInt();
List<Point> list = new ArrayList<>();
for(int i = 0; i < n; i++)
{
Point point = new Point();
point.x = sc.nextDouble();
point.y = sc.nextDouble();
list.add(point);
}
double res = pintoToPolygonMinDist(p, list);
System.out.printf("%.3f", res);
}
}
3. 参考:
- 商汤笔试-开发大类B卷编程题投票
- 商汤科技9.16 数据开发笔试(B卷)
- 商汤第一题代码
- 判断点与多边形的最小距离
- 商汤科技2020-8-20开发笔试A卷